<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
session_start();

if (!isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}

// Role-based access control
$allowed_roles = ['admin', 'registrar', 'headteacher'];

if (!in_array($_SESSION['role'], $allowed_roles)) {
    header('Location: dashboard.php?error=access_denied');
    exit;
}

require_once 'config.php';
require_once __DIR__ . '/includes/upload_validator.php';
$conn = getDBConnection();

// Handle POST form submissions
$message = '';
$messageType = '';

// Function to generate next student ID
function generateStudentId($conn) {
    $result = $conn->query("SELECT student_id FROM students WHERE student_id REGEXP '^STU[0-9]+$' ORDER BY CAST(SUBSTRING(student_id, 4) AS UNSIGNED) DESC LIMIT 1");
    
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $lastId = $row['student_id'];
        $number = intval(substr($lastId, 3));
        $nextNumber = $number + 1;
    } else {
        $nextNumber = 1;
    }
    
    return 'STU' . str_pad($nextNumber, 3, '0', STR_PAD_LEFT);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Add Student
    if (isset($_POST['action']) && $_POST['action'] === 'add') {
        $student_id = generateStudentId($conn);
        // Use trim() not sanitize() — prepared statements handle SQL safety;
        // HTML-encoding is done at output time by safeHtml()/esc().
        $first_name = trim((string) ($_POST['first_name'] ?? ''));
        $last_name  = trim((string) ($_POST['last_name']  ?? ''));
        $class      = trim((string) ($_POST['class']      ?? ''));
        $section    = trim((string) ($_POST['section']    ?? ''));
        $status     = trim((string) ($_POST['status']     ?? 'active'));

        // Validate required fields
        $errors = [];
        if (empty($first_name)) $errors[] = "First name is required";
        if (empty($last_name))  $errors[] = "Last name is required";
        if (empty($class))      $errors[] = "Class is required";

        // At least one parent contact
        $father_phone    = trim((string) ($_POST['father_phone']            ?? ''));
        $mother_phone    = trim((string) ($_POST['mother_phone']            ?? ''));
        $emergency_phone = trim((string) ($_POST['emergency_contact_phone'] ?? ''));

        if (empty($father_phone) && empty($mother_phone) && empty($emergency_phone)) {
            $errors[] = "At least one contact number (Father, Mother, or Emergency) is required";
        }

        if (!empty($errors)) {
            $message = implode("<br>", $errors);
            $messageType = 'danger';
        } else {
            // Get all other fields
            $sex                    = trim((string) ($_POST['sex']                    ?? ''));
            $date_of_birth          = trim((string) ($_POST['date_of_birth']          ?? '')) ?: null;
            $place_of_birth         = trim((string) ($_POST['place_of_birth']         ?? ''));
            $nationality            = trim((string) ($_POST['nationality']            ?? ''));
            $house_no               = trim((string) ($_POST['house_no']               ?? ''));
            $father_name            = trim((string) ($_POST['father_name']            ?? ''));
            $father_occupation      = trim((string) ($_POST['father_occupation']      ?? ''));
            $father_address         = trim((string) ($_POST['father_address']         ?? ''));
            $mother_name            = trim((string) ($_POST['mother_name']            ?? ''));
            $mother_occupation      = trim((string) ($_POST['mother_occupation']      ?? ''));
            $mother_address         = trim((string) ($_POST['mother_address']         ?? ''));
            $religion               = trim((string) ($_POST['religion']               ?? ''));
            $parents_live_together  = trim((string) ($_POST['parents_live_together']  ?? ''));
            $guardian_relationship  = trim((string) ($_POST['guardian_relationship']  ?? ''));
            $has_handicap           = trim((string) ($_POST['has_handicap']           ?? ''));
            $handicap_description   = trim((string) ($_POST['handicap_description']   ?? ''));
            $languages_spoken       = trim((string) ($_POST['languages_spoken']       ?? ''));
            $last_school            = trim((string) ($_POST['last_school']            ?? ''));
            $last_class             = trim((string) ($_POST['last_class']             ?? ''));
            $emergency_contact_name    = trim((string) ($_POST['emergency_contact_name']    ?? ''));
            $emergency_contact_address = trim((string) ($_POST['emergency_contact_address'] ?? ''));
            $emergency_contact_phone   = trim((string) ($_POST['emergency_contact_phone']   ?? ''));
            $email   = trim((string) ($_POST['email']   ?? ''));
            $address = trim((string) ($_POST['address'] ?? ''));

            // Handle photo upload
            $photo_path = null;
            if (!empty($_FILES['photo']['name'])) {
                $photo_path = save_uploaded_image($_FILES['photo'], 'uploads/students', $photoErr);
            } elseif (!empty($_POST['photo_data'])) {
                $photo_path = save_base64_image((string) $_POST['photo_data'], 'uploads/students', $photoErr);
            }

            // Handle signature
            $signature_path = null;
            if (!empty($_POST['signature_data'])) {
                $data = $_POST['signature_data'];
                list($type, $data) = explode(';', $data);
                list(, $data) = explode(',', $data);
                $data = base64_decode($data);
                $signature_path = "uploads/students/sig_" . time() . ".png";
                file_put_contents($signature_path, $data);
            }

            $stmt = $conn->prepare("INSERT INTO students (
                student_id, first_name, last_name, sex, date_of_birth, place_of_birth,
                nationality, house_no, father_name, father_occupation, father_address,
                father_phone, mother_name, mother_occupation, mother_address, mother_phone,
                religion, parents_live_together, guardian_relationship, has_handicap,
                handicap_description, languages_spoken, last_school, last_class,
                emergency_contact_name, emergency_contact_address, emergency_contact_phone,
                photo_path, signature_path, class, section, email, address, status
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

            $stmt->bind_param("ssssssssssssssssssssssssssssssssss", 
                $student_id, $first_name, $last_name, $sex, $date_of_birth, $place_of_birth,
                $nationality, $house_no, $father_name, $father_occupation, $father_address,
                $father_phone, $mother_name, $mother_occupation, $mother_address, $mother_phone,
                $religion, $parents_live_together, $guardian_relationship, $has_handicap,
                $handicap_description, $languages_spoken, $last_school, $last_class,
                $emergency_contact_name, $emergency_contact_address, $emergency_contact_phone,
                $photo_path, $signature_path, $class, $section, $email, $address, $status
            );

            if ($stmt->execute()) {
                $message = 'Student added successfully!';
                $messageType = 'success';
            } else {
                $message = 'Failed to add student: ' . $stmt->error;
                $messageType = 'danger';
                error_log("Student insert error: " . $stmt->error);
            }
            $stmt->close();
        }
    }
    
    // Update Student
    elseif (isset($_POST['action']) && $_POST['action'] === 'update') {
        $id = intval($_POST['id'] ?? 0);

        // Use trim() not sanitize() — prepared statements handle SQL safety;
        // HTML-encoding is done at output time by safeHtml()/esc().
        $student_id             = trim((string) ($_POST['student_id']            ?? ''));
        $first_name             = trim((string) ($_POST['first_name']            ?? ''));
        $last_name              = trim((string) ($_POST['last_name']             ?? ''));
        $sex                    = trim((string) ($_POST['sex']                   ?? ''));
        $date_of_birth          = trim((string) ($_POST['date_of_birth']         ?? '')) ?: null;
        $place_of_birth         = trim((string) ($_POST['place_of_birth']        ?? ''));
        $nationality            = trim((string) ($_POST['nationality']           ?? ''));
        $house_no               = trim((string) ($_POST['house_no']              ?? ''));
        $class                  = trim((string) ($_POST['class']                 ?? ''));
        $section                = trim((string) ($_POST['section']               ?? ''));
        $religion               = trim((string) ($_POST['religion']              ?? ''));
        $parents_live_together  = trim((string) ($_POST['parents_live_together'] ?? ''));
        $father_name            = trim((string) ($_POST['father_name']           ?? ''));
        $father_occupation      = trim((string) ($_POST['father_occupation']     ?? ''));
        $father_address         = trim((string) ($_POST['father_address']        ?? ''));
        $father_phone           = trim((string) ($_POST['father_phone']          ?? ''));
        $mother_name            = trim((string) ($_POST['mother_name']           ?? ''));
        $mother_occupation      = trim((string) ($_POST['mother_occupation']     ?? ''));
        $mother_address         = trim((string) ($_POST['mother_address']        ?? ''));
        $mother_phone           = trim((string) ($_POST['mother_phone']          ?? ''));
        $guardian_relationship  = trim((string) ($_POST['guardian_relationship'] ?? ''));
        $parent_name            = trim((string) ($_POST['parent_name']           ?? ''));
        $phone                  = trim((string) ($_POST['phone']                 ?? ''));
        $email                  = trim((string) ($_POST['email']                 ?? ''));
        $address                = trim((string) ($_POST['address']               ?? ''));
        $has_handicap           = trim((string) ($_POST['has_handicap']          ?? ''));
        $handicap_description   = trim((string) ($_POST['handicap_description']  ?? ''));
        $languages_spoken       = trim((string) ($_POST['languages_spoken']      ?? ''));
        $last_school            = trim((string) ($_POST['last_school']           ?? ''));
        $last_class             = trim((string) ($_POST['last_class']            ?? ''));
        $emergency_contact_name    = trim((string) ($_POST['emergency_contact_name']    ?? ''));
        $emergency_contact_address = trim((string) ($_POST['emergency_contact_address'] ?? ''));
        $emergency_contact_phone   = trim((string) ($_POST['emergency_contact_phone']   ?? ''));
        $status                 = trim((string) ($_POST['status']                ?? 'active'));
        
        // Handle photo upload
        $photo_path = null;
        if (!empty($_FILES['photo']['name'])) {
                $photo_path = save_uploaded_image($_FILES['photo'], 'uploads/students', $photoErr);
            } elseif (!empty($_POST['photo_data'])) {
                $photo_path = save_base64_image((string) $_POST['photo_data'], 'uploads/students', $photoErr);
            }
        
        // Handle signature
        $signature_path = null;
        if (!empty($_POST['signature_data'])) {
            $data = $_POST['signature_data'];
            list($type, $data) = explode(';', $data);
            list(, $data) = explode(',', $data);
            $data = base64_decode($data);
            $signature_path = "uploads/students/sig_" . time() . ".png";
            file_put_contents($signature_path, $data);
        }
        
        // Build update query dynamically
        $sql = "UPDATE students SET 
            student_id = ?, first_name = ?, last_name = ?, sex = ?, date_of_birth = ?,
            place_of_birth = ?, nationality = ?, house_no = ?, class = ?, section = ?,
            religion = ?, parents_live_together = ?, father_name = ?, father_occupation = ?,
            father_address = ?, father_phone = ?, mother_name = ?, mother_occupation = ?,
            mother_address = ?, mother_phone = ?, guardian_relationship = ?, parent_name = ?,
            phone = ?, email = ?, address = ?, has_handicap = ?, handicap_description = ?,
            languages_spoken = ?, last_school = ?, last_class = ?, emergency_contact_name = ?,
            emergency_contact_address = ?, emergency_contact_phone = ?, status = ?";
        
        $params = [$student_id, $first_name, $last_name, $sex, $date_of_birth, $place_of_birth,
            $nationality, $house_no, $class, $section, $religion, $parents_live_together,
            $father_name, $father_occupation, $father_address, $father_phone, $mother_name,
            $mother_occupation, $mother_address, $mother_phone, $guardian_relationship,
            $parent_name, $phone, $email, $address, $has_handicap, $handicap_description,
            $languages_spoken, $last_school, $last_class, $emergency_contact_name,
            $emergency_contact_address, $emergency_contact_phone, $status];
        $types = str_repeat('s', count($params));
        
        // Add photo if new one uploaded
        if ($photo_path) {
            $sql .= ", photo_path = ?";
            $params[] = $photo_path;
            $types .= 's';
        } elseif (isset($_POST['remove_photo'])) {
            $sql .= ", photo_path = NULL";
        }
        
        // Add signature if new one uploaded
        if ($signature_path) {
            $sql .= ", signature_path = ?";
            $params[] = $signature_path;
            $types .= 's';
        } elseif (isset($_POST['remove_signature'])) {
            $sql .= ", signature_path = NULL";
        }
        
        $sql .= " WHERE id = ?";
        $params[] = $id;
        $types .= 'i';
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param($types, ...$params);
        
        if ($stmt->execute()) {
            $message = 'Student updated successfully!';
            $messageType = 'success';
        } else {
            $message = 'Failed to update student: ' . $stmt->error;
            $messageType = 'danger';
        }
        $stmt->close();
    }
}

// Handle GET actions (delete)
$block_delete_id = 0;
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    if ($id > 0) {
        // Block delete if student has payment records
        $chk = $conn->prepare("SELECT COUNT(*) AS n FROM payments WHERE student_id = ?");
        $chk->bind_param('i', $id);
        $chk->execute();
        $payment_count = (int) $chk->get_result()->fetch_assoc()['n'];
        $chk->close();

        if ($payment_count > 0) {
            $message = 'This student has ' . $payment_count . ' payment record(s) and cannot be deleted. You can deactivate them instead.';
            $messageType = 'warning';
            $block_delete_id = $id;
        } else {
            $conn->begin_transaction();
            try {
                foreach (['scores', 'attendance', 'notifications', 'exam_results', 'parent_student_link'] as $tbl) {
                    $chkTbl = $conn->query("SHOW TABLES LIKE '{$tbl}'");
                    if ($chkTbl && $chkTbl->num_rows > 0) {
                        $d = $conn->prepare("DELETE FROM `{$tbl}` WHERE student_id = ?");
                        $d->bind_param('i', $id);
                        $d->execute();
                        $d->close();
                    }
                }
                $del = $conn->prepare("DELETE FROM students WHERE id = ?");
                $del->bind_param('i', $id);
                $del->execute();
                $del->close();
                $conn->commit();
                $message = 'Student deleted successfully!';
                $messageType = 'success';
            } catch (Throwable $e) {
                $conn->rollback();
                error_log('Student delete error: ' . $e->getMessage());
                $message = 'Failed to delete student. Please try again.';
                $messageType = 'danger';
            }
        }
    }
}

// Handle deactivate action (offered when delete is blocked by payments)
if (isset($_GET['action']) && $_GET['action'] === 'deactivate' && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    if ($id > 0) {
        $stmt = $conn->prepare("UPDATE students SET status = 'inactive' WHERE id = ?");
        $stmt->bind_param('i', $id);
        if ($stmt->execute()) {
            $message = 'Student deactivated successfully.';
            $messageType = 'success';
        } else {
            $message = 'Failed to deactivate student: ' . $stmt->error;
            $messageType = 'danger';
        }
        $stmt->close();
    }
}

// Get all students
$students = [];
$result = $conn->query("SELECT * FROM students ORDER BY id DESC");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $students[] = $row;
    }
}

// Generate next ID for display
$nextStudentId = generateStudentId($conn);

// Load active classes for dropdowns
$classes_list = [];
$classRes = $conn->query("SELECT class_name FROM classes WHERE is_active = 1 ORDER BY class_name");
if ($classRes) {
    while ($row = $classRes->fetch_assoc()) $classes_list[] = $row['class_name'];
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Students - EduTrack Pro</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" href="css/style.css">
    <!-- Signature Pad -->
    <script src="https://cdn.jsdelivr.net/npm/signature_pad@4.1.7/dist/signature_pad.umd.min.js"></script>
    <!-- Webcam capture -->
    <script src="https://cdn.jsdelivr.net/npm/webcamjs@1.0.26/webcam.min.js"></script>
    <style>
        .required-field label::after {
            content: " *";
            color: red;
        }
        .error-text {
            color: #dc3545;
            font-size: 0.875em;
            margin-top: 0.25rem;
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <!-- Sidebar -->
        <nav id="sidebar" class="sidebar">
        <?php echo buildSidebar(basename($_SERVER['PHP_SELF'])); ?>
        </nav>

        <!-- Main Content -->
        <div class="main-content">
            <!-- Header -->
            <header class="header">
                <button class="btn-toggle" id="sidebarToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="header-right">
                    <div class="dropdown">
                        <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user-circle me-2"></i><?php echo htmlspecialchars((string) ($_SESSION['full_name'] ?? '')); ?>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="settings.php"><i class="fas fa-cog me-2"></i>Settings</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
                        </ul>
                    </div>
                </div>
            </header>

            <!-- Page Content -->
            <main class="content">
                <div class="content-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h2><i class="fas fa-users me-2"></i>Student Management</h2>
                            <p>Manage student records and information</p>
                        </div>
                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addStudentModal">
                            <i class="fas fa-plus me-2"></i>Add Student
                        </button>
                    </div>
                </div>

                <!-- Alert Message -->
                <?php if ($message): ?>
                <div class="alert alert-<?php echo htmlspecialchars($messageType); ?> alert-dismissible fade show" role="alert">
                    <?php echo htmlspecialchars($message); ?>
                    <?php if ($block_delete_id > 0): ?>
                    <div class="mt-2">
                        <a href="students.php?action=deactivate&id=<?php echo $block_delete_id; ?>"
                           class="btn btn-sm btn-warning"
                           onclick="return confirm('Deactivate this student instead of deleting?')">
                            <i class="fas fa-user-slash me-1"></i>Deactivate Student Instead
                        </a>
                    </div>
                    <?php endif; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>

                <!-- Students Table -->
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-list me-2"></i>All Students</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover" id="studentsTable">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Name</th>
                                        <th>Class</th>
                                        <th>Section</th>
                                        <th>Father's Name</th>
                                        <th>Father's Phone</th>
                                        <th>Mother's Name</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($students)): ?>
                                        <tr>
                                            <td colspan="9" class="text-center py-5">
                                                <div class="empty-state">
                                                    <i class="fas fa-user-graduate"></i>
                                                    <h4>No Students Found</h4>
                                                    <p>Add your first student to get started</p>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($students as $student): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($student['student_id']); ?></td>
                                                <td><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></td>
                                                <td><?php echo htmlspecialchars($student['class']); ?></td>
                                                <td><?php echo htmlspecialchars($student['section']); ?></td>
                                                <td><?php echo htmlspecialchars($student['father_name']); ?></td>
                                                <td><?php echo htmlspecialchars($student['father_phone']); ?></td>
                                                <td><?php echo htmlspecialchars($student['mother_name']); ?></td>
                                                <td>
                                                    <span class="badge badge-<?php echo $student['status'] === 'active' ? 'success' : 'danger'; ?>">
                                                        <?php echo ucfirst($student['status']); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <div class="action-buttons">
                                                        <button class="action-btn view" onclick="viewStudent(<?php echo $student['id']; ?>)" title="View">
                                                            <i class="fas fa-eye"></i>
                                                        </button>
                                                        <button class="action-btn edit" onclick="editStudent(<?php echo $student['id']; ?>)" title="Edit">
                                                            <i class="fas fa-edit"></i>
                                                        </button>
                                                        <a href="students.php?action=delete&id=<?php echo $student['id']; ?>" class="action-btn delete" title="Delete" onclick="return confirm('Are you sure you want to delete this student?');">
                                                            <i class="fas fa-trash"></i>
                                                        </a>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </main>

            <!-- Footer -->
            <footer class="footer">
                <p>&copy; 2024 EduTrack Pro. All rights reserved.</p>
            </footer>
        </div>
    </div>

    <!-- Add Student Modal -->
    <div class="modal fade" id="addStudentModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-user-plus me-2"></i>Add New Student</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                
                <form method="POST" action="students.php" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="add">
                    
                    <div class="modal-body">
                        <!-- Nav tabs -->
                        <ul class="nav nav-tabs" id="studentFormTabs" role="tablist">
                            <li class="nav-item"><div class="nav-link active" data-bs-toggle="tab" data-bs-target="#personal">Personal Info</div></li>
                            <li class="nav-item"><div class="nav-link" data-bs-toggle="tab" data-bs-target="#parents">Parents/Guardian</div></li>
                            <li class="nav-item"><div class="nav-link" data-bs-toggle="tab" data-bs-target="#medical">Medical & Languages</div></li>
                            <li class="nav-item"><div class="nav-link" data-bs-toggle="tab" data-bs-target="#school">School History</div></li>
                            <li class="nav-item"><div class="nav-link" data-bs-toggle="tab" data-bs-target="#emergency">Emergency</div></li>
                            <li class="nav-item"><div class="nav-link" data-bs-toggle="tab" data-bs-target="#media">Photo & Signature</div></li>
                        </ul>

                        <!-- Tab panes -->
                        <div class="tab-content mt-3">
                            <!-- Personal Info -->
                            <div class="tab-pane fade show active" id="personal">
                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">First Name *</label>
                                        <input type="text" class="form-control" name="first_name" required>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Last Name *</label>
                                        <input type="text" class="form-control" name="last_name" required>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Sex *</label>
                                        <select class="form-select" name="sex" required>
                                            <option value="">Select</option>
                                            <option value="Male">Male</option>
                                            <option value="Female">Female</option>
                                            <option value="Other">Other</option>
                                        </select>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Date of Birth *</label>
                                        <input type="date" class="form-control" name="date_of_birth" required>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Place of Birth</label>
                                        <input type="text" class="form-control" name="place_of_birth">
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Nationality</label>
                                        <input type="text" class="form-control" name="nationality">
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">House No.</label>
                                        <input type="text" class="form-control" name="house_no">
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Class *</label>
                                        <select class="form-select" name="class" required>
                                            <option value="">Select Class</option>
                                            <?php foreach ($classes_list as $cls): ?>
                                            <option value="<?= htmlspecialchars($cls) ?>"><?= htmlspecialchars($cls) ?></option>
                                            <?php endforeach; ?>
                                            <?php if (empty($classes_list)): ?>
                                            <option disabled>No active classes — add classes in Class Management</option>
                                            <?php endif; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Section</label>
                                        <input type="text" class="form-control" name="section">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Religious Denomination</label>
                                        <input type="text" class="form-control" name="religion">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Do parents live together?</label>
                                        <select class="form-select" name="parents_live_together">
                                            <option value="">Select</option>
                                            <option value="Yes">Yes</option>
                                            <option value="No">No</option>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <!-- Parents/Guardian -->
                            <div class="tab-pane fade" id="parents">
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle me-2"></i> At least the contact number and the names (Father, Mother, or Emergency) are required.
                                </div>
                                <h6>Father's Information</h6>
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Father's Name *</label>
                                        <input type="text" class="form-control" name="father_name" required>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Occupation *</label>
                                        <input type="text" class="form-control" name="father_occupation" required>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Address</label>
                                        <textarea class="form-control" name="father_address" rows="2"></textarea>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Phone *</label>
                                        <input type="tel" class="form-control" name="father_phone" id="father_phone" required>
                                    </div>
                                </div>
                                <hr>
                                <h6>Mother's Information</h6>
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Mother's Name *</label>
                                        <input type="text" class="form-control" name="mother_name" required>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Occupation *</label>
                                        <input type="text" class="form-control" name="mother_occupation" required>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Address</label>
                                        <textarea class="form-control" name="mother_address" rows="2"></textarea>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Phone *</label>
                                        <input type="tel" class="form-control" name="mother_phone" id="mother_phone" required>
                                    </div>
                                </div>
                                <hr>
                                <h6>Guardian (if applicable)</h6>
                                <div class="row">
                                    <div class="col-md-12 mb-3">
                                        <label class="form-label">Relationship to child</label>
                                        <input type="text" class="form-control" name="guardian_relationship">
                                    </div>
                                </div>
                            </div>

                            <!-- Medical & Languages -->
                            <div class="tab-pane fade" id="medical">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Does child have a handicap/allergy?</label>
                                        <select class="form-select" name="has_handicap" id="has_handicap">
                                            <option value="">Select</option>
                                            <option value="Yes">Yes</option>
                                            <option value="No">No</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6 mb-3" id="handicap_desc_group" style="display:none;">
                                        <label class="form-label">If yes, describe</label>
                                        <textarea class="form-control" name="handicap_description" rows="2"></textarea>
                                    </div>
                                    <div class="col-md-12 mb-3">
                                        <label class="form-label">Languages spoken by child</label>
                                        <input type="text" class="form-control" name="languages_spoken" placeholder="e.g., English, Twi">
                                    </div>
                                </div>
                            </div>

                            <!-- School History -->
                            <div class="tab-pane fade" id="school">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Last School Attended</label>
                                        <input type="text" class="form-control" name="last_school">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Last Class</label>
                                        <input type="text" class="form-control" name="last_class">
                                    </div>
                                </div>
                            </div>

                            <!-- Emergency Contact -->
                            <div class="tab-pane fade" id="emergency">
                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Contact Name</label>
                                        <input type="text" class="form-control" name="emergency_contact_name">
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Address</label>
                                        <input type="text" class="form-control" name="emergency_contact_address">
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Phone * (At least one parent/emergency contact required)</label>
                                        <input type="tel" class="form-control" name="emergency_contact_phone" id="emergency_phone">
                                    </div>
                                </div>
                            </div>

                            <!-- Photo & Signature -->
                            <div class="tab-pane fade" id="media">
                                <div class="row">
                                    <!-- Photo Section -->
                                    <div class="col-md-6">
                                        <div class="card">
                                            <div class="card-header bg-light">
                                                <h6 class="mb-0"><i class="fas fa-camera me-2"></i>Student Photo</h6>
                                            </div>
                                            <div class="card-body">
                                                <div id="webcam-container" class="mb-3 text-center"></div>
                                                <div id="photo-preview" class="mb-3 text-center"></div>
                                                <div class="d-grid gap-2 mb-3">
                                                    <button type="button" class="btn btn-primary" onclick="capturePhoto()">
                                                        <i class="fas fa-camera me-2"></i>Capture Photo
                                                    </button>
                                                </div>
                                                <div class="text-center mb-3">
                                                    <span class="bg-light px-3 py-1 rounded-pill">OR</span>
                                                </div>
                                                <div class="mb-3">
                                                    <label class="form-label">Upload Photo</label>
                                                    <input type="file" class="form-control" id="photo-file" name="photo" accept="image/*">
                                                </div>
                                                <div class="d-grid">
                                                    <button type="button" class="btn btn-outline-secondary" onclick="retakePhoto()">
                                                        <i class="fas fa-redo me-2"></i>Retake/Clear
                                                    </button>
                                                </div>
                                                <input type="hidden" name="photo_data" id="photo_data">
                                                <small class="text-muted">Supported formats: JPG, PNG (Max 2MB)</small>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Signature Section -->
                                    <div class="col-md-6">
                                        <div class="card">
                                            <div class="card-header bg-light">
                                                <h6 class="mb-0"><i class="fas fa-pen me-2"></i>Signature</h6>
                                            </div>
                                            <div class="card-body">
                                                <canvas id="signature-pad" class="border rounded w-100" width="300" height="150"></canvas>
                                                <div id="signature-preview" class="mt-3 text-center"></div>
                                                <div class="row mt-3">
                                                    <div class="col-6">
                                                        <button type="button" class="btn btn-outline-danger w-100" onclick="clearSignature()">
                                                            <i class="fas fa-eraser me-2"></i>Clear
                                                        </button>
                                                    </div>
                                                    <div class="col-6">
                                                        <button type="button" class="btn btn-success w-100" onclick="saveSignature()">
                                                            <i class="fas fa-save me-2"></i>Save
                                                        </button>
                                                    </div>
                                                </div>
                                                <input type="hidden" name="signature_data" id="signature_data">
                                                <small class="text-muted mt-2 d-block">Draw your signature using mouse or touch</small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary" onclick="return validateContactForms()">Add Student</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit Student Modal -->
    <div class="modal fade" id="editStudentModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-user-edit me-2"></i>Edit Student</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" action="students.php" id="editStudentForm" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="update">
                    <input type="hidden" name="id" id="editStudentId">
                    <div class="modal-body" id="editStudentContent">
                        <!-- Content loaded via AJAX -->
                        <p class="text-center">Loading...</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Update Student</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- View Student Modal -->
    <div class="modal fade" id="viewStudentModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-user me-2"></i>Student Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="viewStudentContent">
                    <p class="text-center">Loading...</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script src="js/main.js"></script>
    <script>
        $(document).ready(function() {
            // Initialize DataTable
            $('#studentsTable').DataTable({
                pageLength: 10,
                lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                order: [[1, 'asc']],
                language: {
                    emptyTable: "No students found"
                }
            });
        });

        // Edit Student - Load data via AJAX
        function editStudent(id) {
            $('#editStudentId').val(id);
            $('#editStudentModal').modal('show');
            
            $.ajax({
                url: 'ajax/students.php?action=edit&id=' + id,
                type: 'GET',
                success: function(response) {
                    $('#editStudentContent').html(response);
                },
                error: function() {
                    $('#editStudentContent').html('<p class="text-danger">Failed to load student data</p>');
                }
            });
        }

        // View Student
        function viewStudent(id) {
            $('#viewStudentModal').modal('show');
            $('#viewStudentContent').html('<p class="text-center">Loading...</p>');
            
            $.ajax({
                url: 'ajax/students.php?action=view&id=' + id,
                type: 'GET',
                success: function(response) {
                    $('#viewStudentContent').html(response);
                },
                error: function() {
                    $('#viewStudentContent').html('<p class="text-danger">Failed to load student data</p>');
                }
            });
        }
        
        // Validate that at least one contact number is provided
        function validateContactForms() {
            const fatherPhone = document.getElementById('father_phone')?.value.trim();
            const motherPhone = document.getElementById('mother_phone')?.value.trim();
            const emergencyPhone = document.getElementById('emergency_phone')?.value.trim();
            
            if (!fatherPhone && !motherPhone && !emergencyPhone) {
                alert('Please provide at least one contact number (Father, Mother, or Emergency)');
                return false;
            }
            return true;
        }

        // Signature Pad
        let canvas = document.getElementById('signature-pad');
        let signaturePad = new SignaturePad(canvas, {
            backgroundColor: 'rgb(255,255,255)'
        });

        function clearSignature() {
            signaturePad.clear();
            document.getElementById('signature_data').value = '';
        }

        function saveSignature() {
            if (signaturePad.isEmpty()) {
                alert('Please provide a signature.');
                return;
            }
            const dataURL = signaturePad.toDataURL();
            document.getElementById('signature_data').value = dataURL;
            
            const previewHtml = '<img src="' + dataURL + '" style="max-width:100%; max-height:100px; border:1px solid #ddd; padding:5px;">';
            document.getElementById('signature-preview').innerHTML = previewHtml;
            
            alert('Signature captured!');
        }

        // Initialize webcam when modal is shown
        $('#addStudentModal').on('shown.bs.modal', function() {
            Webcam.set({
                width: 500,
                height: 240,
                image_format: 'jpeg',
                jpeg_quality: 90,
                force_flash: false
            });
            
            Webcam.attach('#webcam-container');
        });

        // Stop webcam when modal is hidden
        $('#addStudentModal').on('hidden.bs.modal', function() {
            Webcam.reset();
            document.getElementById('photo-preview').innerHTML = '';
            document.getElementById('signature-preview').innerHTML = '';
            document.getElementById('photo_data').value = '';
            document.getElementById('signature_data').value = '';
            signaturePad.clear();
        });

        function capturePhoto() {
            Webcam.snap(function(data_uri) {
                document.getElementById('photo_data').value = data_uri;
                
                const previewHtml = '<img src="' + data_uri + '" style="max-width:100%; max-height:200px; border:1px solid #ddd; padding:5px;">';
                document.getElementById('photo-preview').innerHTML = previewHtml;
                
                alert('Photo captured!');
            });
        }

        // Handle file upload preview
        document.getElementById('photo-file')?.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    document.getElementById('photo-preview').innerHTML = '<img src="' + e.target.result + '" style="max-width:100%; max-height:200px; border:1px solid #ddd; padding:5px;">';
                    document.getElementById('photo_data').value = '';
                };
                reader.readAsDataURL(file);
            }
        });

        // Show/hide handicap description
        document.addEventListener('DOMContentLoaded', function() {
            const hasHandicap = document.getElementById('has_handicap');
            if (hasHandicap) {
                hasHandicap.addEventListener('change', function() {
                    document.getElementById('handicap_desc_group').style.display = this.value === 'Yes' ? 'block' : 'none';
                });
            }
        });

        // Retake photo
        function retakePhoto() {
            document.getElementById('photo_data').value = '';
            document.getElementById('photo-preview').innerHTML = '';
            document.getElementById('photo-file').value = '';
        }
    </script>
</body>
</html>
