<?php
require_once '../includes/config.php';

// Production: suppress display errors to avoid header issues
ini_set('display_errors', 0);

// Check if user is logged in and is admin
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true || $_SESSION['role'] !== 'admin') {
    header('Location: ../auth/login.php');
    exit();
}

$title = "Edit Student";

// Initialize variables
$student_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$message = '';
$message_type = '';

// Get student data
$student = null;
if ($student_id > 0) {
    $sql = "SELECT s.*, g.name as gender_name, c.code as course_code, c.name as course_name, 
                   d.code as department_code, d.name as department_name,
                   sc.code as school_code, sc.name as school_name
            FROM students s
            LEFT JOIN genders g ON s.gender_id = g.id
            LEFT JOIN courses c ON s.course_id = c.id
            LEFT JOIN departments d ON s.department_id = d.id
            LEFT JOIN schools sc ON s.school_id = sc.id
            WHERE s.id = ?";
    
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, 'i', $student_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    
    if ($result && mysqli_num_rows($result) > 0) {
        $student = mysqli_fetch_assoc($result);
    } else {
        $_SESSION['message'] = 'Student not found!';
        $_SESSION['message_type'] = 'danger';
        header('Location: manage_students.php');
        exit();
    }
    mysqli_stmt_close($stmt);
} else {
    $_SESSION['message'] = 'Invalid student ID!';
    $_SESSION['message_type'] = 'danger';
    header('Location: manage_students.php');
    exit();
}

// Get dropdown data
$genders = [];
$courses = [];
$departments = [];
$schools = [];

// Genders
$result = mysqli_query($conn, "SELECT * FROM genders ORDER BY id");
while ($row = mysqli_fetch_assoc($result)) {
    $genders[] = $row;
}

// Courses
$result = mysqli_query($conn, "SELECT * FROM courses WHERE status = 1 ORDER BY code");
while ($row = mysqli_fetch_assoc($result)) {
    $courses[] = $row;
}

// Departments
$result = mysqli_query($conn, "SELECT * FROM departments WHERE status = 1 ORDER BY code");
while ($row = mysqli_fetch_assoc($result)) {
    $departments[] = $row;
}

// Schools
$result = mysqli_query($conn, "SELECT * FROM schools WHERE status = 1 ORDER BY code");
while ($row = mysqli_fetch_assoc($result)) {
    $schools[] = $row;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_student'])) {
    // Prefer POSTed id if present
    $student_id = isset($_POST['id']) ? intval($_POST['id']) : $student_id;
    
    $student_data = [
        'student_id' => mysqli_real_escape_string($conn, trim($_POST['student_id'])),
        'full_name' => mysqli_real_escape_string($conn, trim($_POST['full_name'])),
        'gender_id' => intval($_POST['gender_id']),
        'year_level' => intval($_POST['year_level']),
        'course_id' => intval($_POST['course_id']),
        'department_id' => intval($_POST['department_id']),
        'school_id' => intval($_POST['school_id']),
        'birth_date' => (isset($_POST['birth_date']) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $_POST['birth_date']) && $_POST['birth_date'] !== '0000-00-00') ? mysqli_real_escape_string($conn, $_POST['birth_date']) : NULL,
        'contact_number' => mysqli_real_escape_string($conn, trim($_POST['contact_number'])),
        'email' => mysqli_real_escape_string($conn, trim($_POST['email'])),
        'address' => mysqli_real_escape_string($conn, trim($_POST['address'])),
        'status' => isset($_POST['status']) ? 1 : 0
    ];

    // Validate required fields
    $required_fields = ['student_id', 'full_name', 'gender_id', 'year_level', 'course_id', 'department_id', 'school_id'];
    $valid = true;
    
    foreach ($required_fields as $field) {
        if (empty($student_data[$field])) {
            $valid = false;
            $message = "Missing required field: $field";
            $message_type = 'danger';
            break;
        }
    }

    // Validate email format if provided
    if ($valid && !empty($student_data['email']) && !filter_var($student_data['email'], FILTER_VALIDATE_EMAIL)) {
        $valid = false;
        $message = 'Please enter a valid email address.';
        $message_type = 'danger';
    }

    // Check for duplicate student ID (excluding current student)
    if ($valid) {
        $check_sql = "SELECT id FROM students WHERE student_id = ? AND id != ?";
        $stmt = mysqli_prepare($conn, $check_sql);
        mysqli_stmt_bind_param($stmt, 'si', $student_data['student_id'], $student_id);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_store_result($stmt);
        
        if (mysqli_stmt_num_rows($stmt) > 0) {
            $message = 'Student ID already exists. Please use a different Student ID.';
            $message_type = 'danger';
            $valid = false;
        }
        mysqli_stmt_close($stmt);
    }

    if ($valid) {
        // Build SQL query allowing NULLs for optional fields
        $setParts = [
            'student_id = ?', 'full_name = ?', 'gender_id = ?', 'year_level = ?',
            'course_id = ?', 'department_id = ?', 'school_id = ?', 'status = ?', 'updated_at = NOW()'
        ];
        $types = 'ssiiiiii';
        $params = [
            $student_data['student_id'],
            $student_data['full_name'],
            $student_data['gender_id'],
            $student_data['year_level'],
            $student_data['course_id'],
            $student_data['department_id'],
            $student_data['school_id'],
            $student_data['status']
        ];
        
        // Optional fields: set to NULL when empty
        if (!empty($student_data['birth_date'])) {
            $setParts[] = 'birth_date = ?';
            $types .= 's';
            $params[] = $student_data['birth_date'];
        } else {
            $setParts[] = 'birth_date = NULL';
        }
        if (!empty($student_data['contact_number'])) {
            $setParts[] = 'contact_number = ?';
            $types .= 's';
            $params[] = $student_data['contact_number'];
        } else {
            $setParts[] = 'contact_number = NULL';
        }
        if (!empty($student_data['email'])) {
            $setParts[] = 'email = ?';
            $types .= 's';
            $params[] = $student_data['email'];
        } else {
            $setParts[] = 'email = NULL';
        }
        if (!empty($student_data['address'])) {
            $setParts[] = 'address = ?';
            $types .= 's';
            $params[] = $student_data['address'];
        } else {
            $setParts[] = 'address = NULL';
        }
        
        $sql = 'UPDATE students SET ' . implode(', ', $setParts) . ' WHERE id = ?';
        $types .= 'i';
        $params[] = $student_id;
        
        $stmt = mysqli_prepare($conn, $sql);
        if (!$stmt) {
            $message = 'Error preparing update: ' . mysqli_error($conn);
            $message_type = 'danger';
        } else {
            mysqli_stmt_bind_param($stmt, $types, ...$params);
            
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['message'] = 'Student updated successfully!';
                $_SESSION['message_type'] = 'success';
                header("Location: view_student.php?id=$student_id");
                exit();
            } else {
                $error_msg = mysqli_error($conn);
                $message = 'Error updating student: ' . $error_msg;
                $message_type = 'danger';
            }
            mysqli_stmt_close($stmt);
        }
    }
}

include '../includes/header.php';
?>

<!-- Page Header -->
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h3 mb-2">
                <i class="bi bi-pencil-square me-2"></i> Edit Student
            </h1>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                    <li class="breadcrumb-item"><a href="manage_students.php">Manage Students</a></li>
                    <li class="breadcrumb-item active">Edit Student</li>
                </ol>
            </nav>
        </div>
        <div>
            <a href="manage_students.php" class="btn btn-outline-secondary">
                <i class="bi bi-arrow-left me-2"></i> Back to Students
            </a>
        </div>
    </div>

    <!-- Message Alert -->
    <?php if ($message): ?>
    <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
        <i class="bi bi-<?php echo $message_type == 'success' ? 'check-circle' : 'exclamation-triangle'; ?> me-2"></i>
        <?php echo $message; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <?php endif; ?>

    <?php if ($student): ?>
    <div class="row">
        <div class="col-lg-8">
            <!-- Edit Form Card -->
            <div class="card shadow mb-4">
                <div class="card-header bg-primary text-white">
                    <h6 class="m-0 font-weight-bold">
                        <i class="bi bi-person-lines-fill me-2"></i> Student Information
                    </h6>
                </div>
                <div class="card-body">
                    <form method="POST" action="" id="editStudentForm">
                        <input type="hidden" name="id" value="<?php echo $student_id; ?>">
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Student ID <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="student_id" required 
                                       value="<?php echo htmlspecialchars($student['student_id']); ?>" 
                                       maxlength="50" id="student_id_field">
                                <div class="form-text">Unique student identification number</div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Full Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="full_name" required 
                                       value="<?php echo htmlspecialchars($student['full_name']); ?>" 
                                       maxlength="100" id="full_name_field">
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Gender <span class="text-danger">*</span></label>
                                <select class="form-select" name="gender_id" required id="gender_id_field">
                                    <option value="">Select Gender</option>
                                    <?php foreach ($genders as $gender): ?>
                                        <option value="<?php echo $gender['id']; ?>" 
                                            <?php echo $student['gender_id'] == $gender['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($gender['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Year Level <span class="text-danger">*</span></label>
                                <select class="form-select" name="year_level" required id="year_level_field">
                                    <option value="">Select Year Level</option>
                                    <?php for ($i = 1; $i <= 4; $i++): ?>
                                        <option value="<?php echo $i; ?>"
                                            <?php echo $student['year_level'] == $i ? 'selected' : ''; ?>>
                                            Year <?php echo $i; ?>
                                        </option>
                                    <?php endfor; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label class="form-label">School <span class="text-danger">*</span></label>
                                <select class="form-select" name="school_id" required id="school_id_field">
                                    <option value="">Select School</option>
                                    <?php foreach ($schools as $school): ?>
                                        <option value="<?php echo $school['id']; ?>"
                                            <?php echo $student['school_id'] == $school['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($school['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Department <span class="text-danger">*</span></label>
                                <select class="form-select" name="department_id" required id="department_id_field">
                                    <option value="">Select Department</option>
                                    <?php foreach ($departments as $department): ?>
                                        <option value="<?php echo $department['id']; ?>"
                                            <?php echo $student['department_id'] == $department['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($department['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Course <span class="text-danger">*</span></label>
                                <select class="form-select" name="course_id" required id="course_id_field">
                                    <option value="">Select Course</option>
                                    <?php foreach ($courses as $course): ?>
                                        <option value="<?php echo $course['id']; ?>"
                                            <?php echo $student['course_id'] == $course['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($course['code']); ?> - <?php echo htmlspecialchars($course['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Birth Date</label>
                                <input type="date" class="form-control" name="birth_date" 
                                       value="<?php echo $student['birth_date']; ?>" 
                                       max="<?php echo date('Y-m-d'); ?>" id="birth_date_field">
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Email Address</label>
                                <input type="email" class="form-control" name="email" 
                                       value="<?php echo htmlspecialchars($student['email']); ?>" 
                                       maxlength="100" id="email_field">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Contact Number</label>
                                <input type="tel" class="form-control" name="contact_number" 
                                       value="<?php echo htmlspecialchars($student['contact_number']); ?>"
                                       id="contact_number_field">
                            </div>
                            
                            <div class="col-12 mb-3">
                                <label class="form-label">Address</label>
                                <textarea class="form-control" name="address" rows="3" 
                                          maxlength="255" id="address_field"><?php echo htmlspecialchars($student['address']); ?></textarea>
                            </div>
                            
                            <div class="col-12 mb-3">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" role="switch" 
                                           name="status" id="statusSwitch" value="1"
                                           <?php echo $student['status'] == 1 ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="statusSwitch">
                                        Active Student
                                    </label>
                                </div>
                            </div>
                        </div>
                        
                        <div class="d-flex justify-content-between mt-4">
                            <a href="view_student.php?id=<?php echo $student_id; ?>" class="btn btn-secondary">
                                <i class="bi bi-x-circle me-2"></i> Cancel
                            </a>
                            <button type="submit" class="btn btn-primary" name="update_student" id="submitBtn">
                                <i class="bi bi-save me-2"></i> Update Student
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <div class="col-lg-4">
            <!-- Student Summary Card -->
            <div class="card shadow mb-4">
                <div class="card-header bg-info text-white">
                    <h6 class="m-0 font-weight-bold">
                        <i class="bi bi-person-badge me-2"></i> Student Summary
                    </h6>
                </div>
                <div class="card-body">
                    <div class="text-center mb-4">
                        <?php if (!empty($student['picture_path'])): ?>
                            <img src="../<?php echo htmlspecialchars($student['picture_path']); ?>" 
                                 alt="Student Photo" class="rounded-circle mb-3" 
                                 style="width: 120px; height: 120px; object-fit: cover;">
                        <?php else: ?>
                            <div class="bg-primary rounded-circle d-flex align-items-center justify-content-center mx-auto mb-3" 
                                 style="width: 120px; height: 120px;">
                                <i class="bi bi-person" style="font-size: 3rem; color: white;"></i>
                            </div>
                        <?php endif; ?>
                        
                        <h5><?php echo htmlspecialchars($student['full_name']); ?></h5>
                        <p class="text-muted"><?php echo htmlspecialchars($student['student_id']); ?></p>
                        
                        <div class="mb-3">
                            <?php if ($student['status'] == 1): ?>
                                <span class="badge bg-success">
                                    <i class="bi bi-check-circle me-1"></i> Active
                                </span>
                            <?php else: ?>
                                <span class="badge bg-danger">
                                    <i class="bi bi-x-circle me-1"></i> Inactive
                                </span>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="list-group list-group-flush">
                        <div class="list-group-item d-flex justify-content-between align-items-center">
                            <span>Gender</span>
                            <span><?php echo htmlspecialchars($student['gender_name']); ?></span>
                        </div>
                        <div class="list-group-item d-flex justify-content-between align-items-center">
                            <span>Course</span>
                            <span class="fw-bold"><?php echo htmlspecialchars($student['course_code']); ?></span>
                        </div>
                        <div class="list-group-item d-flex justify-content-between align-items-center">
                            <span>Year Level</span>
                            <span class="badge bg-info">Year <?php echo $student['year_level']; ?></span>
                        </div>
                        <div class="list-group-item d-flex justify-content-between align-items-center">
                            <span>Department</span>
                            <span><?php echo htmlspecialchars($student['department_name']); ?></span>
                        </div>
                        <div class="list-group-item d-flex justify-content-between align-items-center">
                            <span>School</span>
                            <span><?php echo htmlspecialchars($student['school_name']); ?></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <?php else: ?>
    <!-- Student Not Found -->
    <div class="card shadow">
        <div class="card-body text-center py-5">
            <i class="bi bi-person-x" style="font-size: 4rem; color: #dc3545;"></i>
            <h3 class="mt-3">Student Not Found</h3>
            <p class="text-muted">The student you're trying to edit does not exist or has been deleted.</p>
            <a href="manage_students.php" class="btn btn-primary mt-3">
                <i class="bi bi-arrow-left me-2"></i> Back to Students List
            </a>
        </div>
    </div>
    <?php endif; ?>
</div>

<?php 
$page_scripts = '
<script>
function validateEditForm() {
    console.log("Validating form...");
    
    // Get form values
    const studentId = document.getElementById("student_id_field").value.trim();
    const fullName = document.getElementById("full_name_field").value.trim();
    const genderId = document.getElementById("gender_id_field").value;
    const yearLevel = document.getElementById("year_level_field").value;
    const schoolId = document.getElementById("school_id_field").value;
    const departmentId = document.getElementById("department_id_field").value;
    const courseId = document.getElementById("course_id_field").value;
    const email = document.getElementById("email_field").value.trim();
    
    // Check required fields
    if (!studentId) {
        alert("Please enter Student ID");
        document.getElementById("student_id_field").focus();
        return false;
    }
    
    if (!fullName) {
        alert("Please enter Full Name");
        document.getElementById("full_name_field").focus();
        return false;
    }
    
    if (!genderId) {
        alert("Please select Gender");
        document.getElementById("gender_id_field").focus();
        return false;
    }
    
    if (!yearLevel) {
        alert("Please select Year Level");
        document.getElementById("year_level_field").focus();
        return false;
    }
    
    if (!schoolId) {
        alert("Please select School");
        document.getElementById("school_id_field").focus();
        return false;
    }
    
    if (!departmentId) {
        alert("Please select Department");
        document.getElementById("department_id_field").focus();
        return false;
    }
    
    if (!courseId) {
        alert("Please select Course");
        document.getElementById("course_id_field").focus();
        return false;
    }
    
    // Validate email format if provided
    if (email && !isValidEmail(email)) {
        alert("Please enter a valid email address");
        document.getElementById("email_field").focus();
        return false;
    }
    
    // Show loading state
    document.getElementById("submitBtn").innerHTML = \'<i class="bi bi-hourglass-split me-2"></i> Updating...\';
    document.getElementById("submitBtn").disabled = true;
    
    console.log("Form validation passed");
    return true;
}

function isValidEmail(email) {
    const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;
    return emailRegex.test(email);
}

// Debug form submission
document.getElementById("editStudentForm").addEventListener("submit", function(e) {
    console.log("Form submitted");
    console.log("Form action:", this.action);
    console.log("Form method:", this.method);
    
    const formData = new FormData(this);
    console.log("Form data:");
    for (let [key, value] of formData.entries()) {
        console.log(key + ": " + value);
    }
});

// Check if form elements exist
document.addEventListener("DOMContentLoaded", function() {
    console.log("DOM loaded");
    console.log("Form exists:", document.getElementById("editStudentForm") !== null);
    console.log("Submit button exists:", document.getElementById("submitBtn") !== null);
    
    // Test form submission via JavaScript
    document.getElementById("editStudentForm").onsubmit = function() {
        console.log("Form onsubmit fired");
        return validateEditForm();
    };
});
</script>
';

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