<?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();
}

// Fetch faculties and departments for dropdowns
$faculties = $conn->query("SELECT id, name FROM faculties");
$departments = $conn->query("SELECT id, name FROM departments");

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Process profile update
    $full_name = $_POST['full_name'];
    $phone = $_POST['phone'];
    $gender = $_POST['gender'];
    $dob = $_POST['dob'];
    $nationality = $_POST['nationality'];
    $faculty_id = $_POST['faculty_id'];
    $department_id = $_POST['department_id'];
    $program = $_POST['program'];
    $year_of_study = $_POST['year_of_study'];
    $semester = $_POST['semester'];
    
    $update_stmt = $conn->prepare("UPDATE students SET full_name=?, phone=?, gender=?, dob=?, nationality=?, faculty_id=?, department_id=?, program=?, year_of_study=?, semester=? WHERE id=?");
    $update_stmt->bind_param("ssssssssssi", $full_name, $phone, $gender, $dob, $nationality, $faculty_id, $department_id, $program, $year_of_study, $semester, $student_id);
    
    if ($update_stmt->execute()) {
        $_SESSION['success'] = "Profile updated successfully!";
        header("Location: profile.php");
        exit();
    } else {
        $_SESSION['error'] = "Error updating profile: " . $conn->error;
    }
}

ob_end_flush();
?>

<!-- Content Area -->
<main class="main-content flex-1 p-6 bg-gray-50 dark:bg-gray-900 overflow-y-auto" style="margin-bottom:80px">
  <!-- Success/Error Messages -->
  <?php if (isset($_SESSION['success'])): ?>
    <div class="mb-4 bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative" role="alert">
      <span class="block sm:inline"><?= $_SESSION['success'] ?></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-green-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['success']); ?>
  <?php endif; ?>
  
  <?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">Edit Profile</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="" class="space-y-6">
      <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <!-- Personal Information -->
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Full Name</label>
          <input type="text" name="full_name" value="<?= htmlspecialchars($student['full_name']) ?>" 
                 class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white" required>
        </div>
        
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Phone Number</label>
          <input type="text" name="phone" value="<?= htmlspecialchars($student['phone']) ?>" 
                 class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white">
        </div>
        
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Gender</label>
          <select name="gender" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white">
            <option value="">Select Gender</option>
            <option value="male" <?= $student['gender'] == 'male' ? 'selected' : '' ?>>Male</option>
            <option value="female" <?= $student['gender'] == 'female' ? 'selected' : '' ?>>Female</option>
            <option value="other" <?= $student['gender'] == 'other' ? 'selected' : '' ?>>Other</option>
          </select>
        </div>
        
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Date of Birth</label>
          <input type="date" name="dob" value="<?= !empty($student['dob']) ? htmlspecialchars($student['dob']) : '' ?>" 
                 class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white">
        </div>
        
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Nationality</label>
          <input type="text" name="nationality" value="<?= !empty($student['nationality']) ? htmlspecialchars($student['nationality']) : '' ?>" 
                 class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white">
        </div>
        
        <!-- Academic Information -->
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Faculty</label>
          <select name="faculty_id" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white">
            <option value="">Select Faculty</option>
            <?php while($faculty = $faculties->fetch_assoc()): ?>
              <option value="<?= $faculty['id'] ?>" <?= $student['faculty_id'] == $faculty['id'] ? 'selected' : '' ?>>
                <?= htmlspecialchars($faculty['name']) ?>
              </option>
            <?php endwhile; ?>
          </select>
        </div>
        
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Department</label>
          <select name="department_id" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white">
            <option value="">Select Department</option>
            <?php while($dept = $departments->fetch_assoc()): ?>
              <option value="<?= $dept['id'] ?>" <?= $student['department_id'] == $dept['id'] ? 'selected' : '' ?>>
                <?= htmlspecialchars($dept['name']) ?>
              </option>
            <?php endwhile; ?>
          </select>
        </div>
        
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Program</label>
          <input type="text" name="program" value="<?= !empty($student['program']) ? htmlspecialchars($student['program']) : '' ?>" 
                 class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white">
        </div>
        
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Year of Study</label>
          <select name="year_of_study" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white">
            <option value="">Select Year</option>
            <option value="1" <?= $student['year_of_study'] == '1' ? 'selected' : '' ?>>Year 1</option>
            <option value="2" <?= $student['year_of_study'] == '2' ? 'selected' : '' ?>>Year 2</option>
            <option value="3" <?= $student['year_of_study'] == '3' ? 'selected' : '' ?>>Year 3</option>
            <option value="4" <?= $student['year_of_study'] == '4' ? 'selected' : '' ?>>Year 4</option>
            <option value="5" <?= $student['year_of_study'] == '5' ? 'selected' : '' ?>>Year 5</option>
          </select>
        </div>
        
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Semester</label>
          <select name="semester" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white">
            <option value="">Select Semester</option>
            <option value="1" <?= $student['semester'] == '1' ? 'selected' : '' ?>>Semester 1</option>
            <option value="2" <?= $student['semester'] == '2' ? 'selected' : '' ?>>Semester 2</option>
          </select>
        </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">
          Save Changes
        </button>
      </div>
    </form>
  </div>
</main>

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