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

// 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 = "Add New Student";

// Initialize variables
$message = '';
$message_type = '';

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

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

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

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

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // Get form data
    $student_id = trim($_POST['student_id'] ?? '');
    $full_name = trim($_POST['full_name'] ?? '');
    $gender_id = intval($_POST['gender_id'] ?? 0);
    $year_level = intval($_POST['year_level'] ?? 0);
    $course_id = intval($_POST['course_id'] ?? 0);
    $department_id = intval($_POST['department_id'] ?? 0);
    $school_id = intval($_POST['school_id'] ?? 0);
    $birth_date = !empty($_POST['birth_date']) ? $_POST['birth_date'] : NULL;
    $contact_number = trim($_POST['contact_number'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $address = trim($_POST['address'] ?? '');
    
    
    // Debug: Check required fields
    if (empty($student_id) || empty($full_name) || $gender_id == 0 || $year_level == 0 || 
        $course_id == 0 || $department_id == 0 || $school_id == 0) {
        $message = 'Please fill in all required fields.';
        $message_type = 'danger';
    }
    
    // Validate email format if provided
    elseif (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $message = 'Please enter a valid email address.';
        $message_type = 'danger';
    }
    
    // Check for duplicate student ID
    else {
        $check_sql = "SELECT id FROM students WHERE student_id = ?";
        $stmt = mysqli_prepare($conn, $check_sql);
        if ($stmt) {
            mysqli_stmt_bind_param($stmt, 's', $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';
            }
            mysqli_stmt_close($stmt);
        }
        
        // If no errors, insert student
        if (empty($message)) {
            // Generate QR code
            $qr_code = 'STU_' . $student_id . '_' . uniqid();
            
            $sql = "INSERT INTO students (
                student_id, qr_code, full_name, gender_id, year_level, 
                course_id, department_id, school_id, birth_date, 
                contact_number, email, address, created_at, updated_at, status
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW(), 1)";
            
            
            $stmt = mysqli_prepare($conn, $sql);
            if ($stmt) {
                // Escape data
                $student_id = mysqli_real_escape_string($conn, $student_id);
                $full_name = mysqli_real_escape_string($conn, $full_name);
                $contact_number = mysqli_real_escape_string($conn, $contact_number);
                $email = mysqli_real_escape_string($conn, $email);
                $address = mysqli_real_escape_string($conn, $address);
                
                // Bind parameters based on birth_date
                if ($birth_date === NULL) {
                    mysqli_stmt_bind_param($stmt, 'sssiiiiissss',
                        $student_id, $qr_code, $full_name, $gender_id, $year_level,
                        $course_id, $department_id, $school_id, null,
                        $contact_number, $email, $address
                    );
                } else {
                    mysqli_stmt_bind_param($stmt, 'sssiiiiissss',
                        $student_id, $qr_code, $full_name, $gender_id, $year_level,
                        $course_id, $department_id, $school_id, $birth_date,
                        $contact_number, $email, $address
                    );
                }
                
                if (mysqli_stmt_execute($stmt)) {
                    $new_student_id = mysqli_insert_id($conn);
                    
                    // Redirect to view the newly added student
                    $_SESSION['flash_message'] = 'Student added successfully!';
                    $_SESSION['flash_type'] = 'success';
                    header("Location: view_student.php?id=$new_student_id");
                    exit();
                } else {
                    $message = 'Error adding student: ' . mysqli_error($conn);
                    $message_type = 'danger';
                }
                mysqli_stmt_close($stmt);
            } else {
                $message = 'Error preparing statement: ' . mysqli_error($conn);
                $message_type = 'danger';
            }
        }
    }
}

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-person-plus me-2"></i> Add New 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">Add 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 mb-4" 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; ?>

    <div class="row">
        <div class="col-lg-8">
            <!-- Add 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="addStudentForm">
                        <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 
                                       placeholder="e.g., 23-0217" maxlength="50"
                                       value="<?php echo isset($_POST['student_id']) ? htmlspecialchars($_POST['student_id']) : ''; ?>">
                                <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 
                                       placeholder="John Lloyd Sumawang" maxlength="100"
                                       value="<?php echo isset($_POST['full_name']) ? htmlspecialchars($_POST['full_name']) : ''; ?>">
                            </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>
                                    <option value="">Select Gender</option>
                                    <?php foreach ($genders as $gender): ?>
                                        <option value="<?php echo $gender['id']; ?>"
                                            <?php echo (isset($_POST['gender_id']) && $_POST['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>
                                    <option value="">Select Year Level</option>
                                    <?php for ($i = 1; $i <= 4; $i++): ?>
                                        <option value="<?php echo $i; ?>"
                                            <?php echo (isset($_POST['year_level']) && $_POST['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>
                                    <option value="">Select School</option>
                                    <?php foreach ($schools as $school): ?>
                                        <option value="<?php echo $school['id']; ?>"
                                            <?php echo (isset($_POST['school_id']) && $_POST['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>
                                    <option value="">Select Department</option>
                                    <?php foreach ($departments as $department): ?>
                                        <option value="<?php echo $department['id']; ?>"
                                            <?php echo (isset($_POST['department_id']) && $_POST['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>
                                    <option value="">Select Course</option>
                                    <?php foreach ($courses as $course): ?>
                                        <option value="<?php echo $course['id']; ?>"
                                            <?php echo (isset($_POST['course_id']) && $_POST['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" 
                                       max="<?php echo date('Y-m-d'); ?>"
                                       value="<?php echo isset($_POST['birth_date']) ? htmlspecialchars($_POST['birth_date']) : ''; ?>">
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Email Address</label>
                                <input type="email" class="form-control" name="email" 
                                       placeholder="student@example.com" maxlength="100"
                                       value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Contact Number</label>
                                <input type="tel" class="form-control" name="contact_number" 
                                       placeholder="0912-345-6789"
                                       value="<?php echo isset($_POST['contact_number']) ? htmlspecialchars($_POST['contact_number']) : ''; ?>">
                                <div class="form-text">Format: 0912-345-6789 or 09123456789</div>
                            </div>
                            
                            <div class="col-12 mb-3">
                                <label class="form-label">Address</label>
                                <textarea class="form-control" name="address" rows="3" 
                                          placeholder="Complete address" maxlength="255"><?php echo isset($_POST['address']) ? htmlspecialchars($_POST['address']) : ''; ?></textarea>
                            </div>
                        </div>
                        
                        <div class="d-flex justify-content-between mt-4">
                            <a href="manage_students.php" class="btn btn-secondary">
                                <i class="bi bi-x-circle me-2"></i> Cancel
                            </a>
                            <button type="submit" class="btn btn-primary" name="add_student">
                                <i class="bi bi-save me-2"></i> Save Student
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <div class="col-lg-4">
            <!-- Guidelines 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-info-circle me-2"></i> Guidelines
                    </h6>
                </div>
                <div class="card-body">
                    <ul class="list-group list-group-flush">
                        <li class="list-group-item">
                            <i class="bi bi-asterisk text-danger me-2"></i>
                            Fields marked with <span class="text-danger">*</span> are required
                        </li>
                        <li class="list-group-item">
                            <i class="bi bi-card-checklist me-2"></i>
                            Student ID must be unique
                        </li>
                        <li class="list-group-item">
                            <i class="bi bi-calendar me-2"></i>
                            Birth date cannot be in the future
                        </li>
                        <li class="list-group-item">
                            <i class="bi bi-envelope me-2"></i>
                            Email must be valid format (optional)
                        </li>
                        <li class="list-group-item">
                            <i class="bi bi-telephone me-2"></i>
                            Contact number should include area code
                        </li>
                        <li class="list-group-item">
                            <i class="bi bi-qr-code me-2"></i>
                            QR code will be automatically generated
                        </li>
                    </ul>
                </div>
            </div>
            
            <!-- Quick Actions Card -->
            <div class="card shadow">
                <div class="card-header bg-warning text-dark">
                    <h6 class="m-0 font-weight-bold">
                        <i class="bi bi-lightning me-2"></i> Quick Actions
                    </h6>
                </div>
                <div class="card-body">
                    <div class="d-grid gap-2">
                        <a href="manage_students.php" class="btn btn-outline-primary">
                            <i class="bi bi-people me-2"></i> View All Students
                        </a>
                        <a href="import_students.php" class="btn btn-outline-success">
                            <i class="bi bi-upload me-2"></i> Import Students
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php 
// SIMPLE JavaScript without complex validation
$page_scripts = '
<script>
$(document).ready(function() {
    // Simple form submission
    $("#addStudentForm").submit(function(e) {
        // Simple validation - just check if required fields are filled
        let valid = true;
        
        // Check required fields
        const requiredFields = [
            "student_id", "full_name", "gender_id", 
            "year_level", "school_id", "department_id", "course_id"
        ];
        
        requiredFields.forEach(field => {
            const element = $("[name=\'" + field + "\']");
            const value = element.val().trim();
            
            if (!value || value === "" || value === "0") {
                valid = false;
                element.addClass("is-invalid");
                element.after(\'<div class="invalid-feedback">This field is required.</div>\');
            } else {
                element.removeClass("is-invalid");
                element.next(".invalid-feedback").remove();
            }
        });
        
        if (!valid) {
            e.preventDefault();
            alert("Please fill in all required fields marked with *");
            return false;
        }
        
        // Show loading state
        $(this).find("button[type=\'submit\']").prop("disabled", true).html(\'<i class="bi bi-hourglass-split me-2"></i> Saving...\');
        return true;
    });
    
    // Remove error classes on input
    $("input, select, textarea").on("input change", function() {
        $(this).removeClass("is-invalid");
        $(this).next(".invalid-feedback").remove();
    });
    
    // Auto-focus first field
    $("input[name=\'student_id\']").focus();
});
</script>
';

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