<?php 
ob_start();
include 'include/header.php';

// Verify session data is complete
if (!isset($_SESSION['user_id'])) {
    session_destroy();
    header("Location: login.php");
    exit();
}

// Database connection
require_once '../config/conn.php';

// Fetch student data
$student_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM students WHERE id = ?");
$stmt->bind_param("i", $student_id);
$stmt->execute();
$result = $stmt->get_result();
$student = $result->fetch_assoc();

if (!$student) {
    $_SESSION['error'] = "Student record not found";
    header("Location: dashboard.php");
    exit();
}

// Handle photo upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_FILES['profile_picture']['name'])) {
    $target_dir = "../uploads/";
    if (!file_exists($target_dir)) {
        mkdir($target_dir, 0777, true);
    }
    
    $file_extension = pathinfo($_FILES["profile_picture"]["name"], PATHINFO_EXTENSION);
    $new_filename = "profile_" . $student_id . "_" . time() . "." . $file_extension;
    $target_file = $target_dir . $new_filename;
    
    // Check if image file is a actual image
    $check = getimagesize($_FILES["profile_picture"]["tmp_name"]);
    if ($check === false) {
        $_SESSION['error'] = "File is not an image.";
    } elseif ($_FILES["profile_picture"]["size"] > 5000000) {
        $_SESSION['error'] = "Sorry, your file is too large (max 5MB).";
    } else {
        $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
        if (!in_array(strtolower($file_extension), $allowed_types)) {
            $_SESSION['error'] = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        } else {
            if (move_uploaded_file($_FILES["profile_picture"]["tmp_name"], $target_file)) {
                // Delete old profile picture if it's not the default
                if (!empty($student['profile_picture']) && $student['profile_picture'] != 'assets/images/default-avatar.png') {
                    @unlink($student['profile_picture']);
                }
                
                $update_stmt = $conn->prepare("UPDATE students SET profile_picture=? WHERE id=?");
                $update_stmt->bind_param("si", $target_file, $student_id);
                
                if ($update_stmt->execute()) {
                    $_SESSION['success'] = "Profile picture updated successfully!";
                    header("Location: profile.php");
                    exit();
                } else {
                    $_SESSION['error'] = "Error updating profile picture in database.";
                }
            } else {
                $_SESSION['error'] = "Sorry, there was an error uploading your file.";
            }
        }
    }
}
ob_end_flush();
?>

<!-- Content Area -->
<main class="main-content flex-1 p-6 bg-gray-50 dark:bg-gray-900 overflow-y-auto">
  <!-- Success/Error Messages -->
  <?php if (isset($_SESSION['error'])): ?>
    <div class="mb-4 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">
      <span class="block sm:inline"><?= $_SESSION['error'] ?></span>
      <span class="absolute top-0 bottom-0 right-0 px-4 py-3" onclick="this.parentElement.style.display='none'">
        <svg class="fill-current h-6 w-6 text-red-500" role="button" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><title>Close</title><path d="M14.348 14.849a1.2 1.2 0 0 1-1.697 0L10 11.819l-2.651 3.029a1.2 1.2 0 1 1-1.697-1.697l2.758-3.15-2.759-3.152a1.2 1.2 0 1 1 1.697-1.697L10 8.183l2.651-3.031a1.2 1.2 0 1 1 1.697 1.697l-2.758 3.152 2.758 3.15a1.2 1.2 0 0 1 0 1.698z"/></svg>
      </span>
    </div>
    <?php unset($_SESSION['error']); ?>
  <?php endif; ?>

  <div class=" dark:bg-gray-800   p-6 border border-gray-100 dark:border-gray-700">
    <div class="flex justify-between items-center mb-6">
      <h2 class="text-xl font-bold dark:text-white">Update Profile Picture</h2>
      <a href="profile.php" class="text-sm text-primary-500 hover:text-primary-600 dark:hover:text-primary-400">
        <i class="fas fa-arrow-left mr-1"></i> Back to Profile
      </a>
    </div>
    
    <form method="POST" action="" enctype="multipart/form-data" class="space-y-6">
      <div class="flex flex-col items-center space-y-6">
        <div class="relative">
          <img id="imagePreview" src="<?= !empty($student['profile_picture']) ? htmlspecialchars($student['profile_picture']) : 'assets/images/default-avatar.png' ?>" 
               alt="Current Profile Picture" 
               class="w-32 h-32 rounded-full object-cover border-4 border-primary-100 dark:border-primary-800">
        </div>
        
        <div class="w-full max-w-md">
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Choose New Photo</label>
          <div class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md dark:border-gray-600">
            <div class="space-y-1 text-center">
              <div class="flex text-sm text-gray-600 dark:text-gray-400 justify-center">
                <label for="profile_picture" class="relative cursor-pointer  rounded-md font-medium text-primary-600 hover:text-primary-500 focus-within:outline-none">
                  <span>Upload a file</span>
                  <input id="profile_picture" name="profile_picture" type="file" class="sr-only" accept="image/*" onchange="previewImage(this)">
                </label>
              </div>
              <p class="text-xs text-gray-500 dark:text-gray-400">
                PNG, JPG, GIF up to 5MB
              </p>
            </div>
          </div>
        </div>
      </div>
      
      <div class="flex justify-end space-x-3 pt-4 border-t dark:border-gray-700">
        <a href="profile.php" class="px-4 py-2 text-sm bg-gray-200 hover:bg-gray-300 rounded-lg dark:bg-gray-600 dark:hover:bg-gray-700 dark:text-white">
          Cancel
        </a>
        <button type="submit" 
                class="px-4 py-2 text-sm bg-primary-500 hover:bg-primary-600 text-white rounded-lg">
          Update Photo
        </button>
      </div>
    </form>
  </div>
</main>

<script>
function previewImage(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
      document.getElementById('imagePreview').src = e.target.result;
    }
    reader.readAsDataURL(input.files[0]);
  }
}
</script>

<?php include 'include/footer.php'; ?>