<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
require_once __DIR__ . '/../includes/require_auth.php';
require_login();

header('Content-Type: application/json');
require_once '../config.php';
require_once '../includes/canteen_helpers.php';

$action = $_GET['action'] ?? '';

// Helper function to safely escape for HTML
function safeHtml($str) {
    if ($str === null) {
        return '';
    }
    return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
}

// Helper function to safely escape for JavaScript
function safeJs($str) {
    if ($str === null) {
        return '';
    }
    return str_replace(array("\r\n", "\r", "\n", "'"), array("\\n", "\\n", "\\n", "\\'"), addslashes($str));
}

// Handle JSON responses for add/update/delete
if (in_array($action, ['add', 'update', 'delete'])) {
    $conn = getDBConnection();
    
    if (!$conn) {
        echo json_encode(['success' => false, 'message' => 'Database connection failed']);
        exit;
    }
    
    try {
        if ($action === 'add') {
            $student_id  = trim((string) ($_POST['student_id']  ?? ''));
            $first_name  = trim((string) ($_POST['first_name']  ?? ''));
            $last_name   = trim((string) ($_POST['last_name']   ?? ''));
            $class       = trim((string) ($_POST['class']       ?? ''));
            $section     = trim((string) ($_POST['section']     ?? ''));
            $parent_name = trim((string) ($_POST['parent_name'] ?? ''));
            $phone       = trim((string) ($_POST['phone']       ?? ''));
            $email       = trim((string) ($_POST['email']       ?? ''));
            $address     = trim((string) ($_POST['address']     ?? ''));
            $status      = trim((string) ($_POST['status']      ?? 'active'));

            if (empty($student_id) || empty($first_name) || empty($last_name) || empty($class)) {
                echo json_encode(['success' => false, 'message' => 'Please fill all required fields']);
                exit;
            }

            $stmt = $conn->prepare("INSERT INTO students (student_id, first_name, last_name, class, section, parent_name, phone, email, address, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("ssssssssss", $student_id, $first_name, $last_name, $class, $section, $parent_name, $phone, $email, $address, $status);

            if ($stmt->execute()) {
                $new_student_db_id = (int) $conn->insert_id;
                // Canteen Module — auto-generate permanent identity QR token
                if ($new_student_db_id > 0 && canteen_is_active()) {
                    $qr_token = canteen_generate_identity_token($new_student_db_id);
                    $qr_now   = date('Y-m-d H:i:s');
                    $qr_stmt  = $conn->prepare(
                        "UPDATE students SET identity_qr_token = ?, identity_qr_generated_at = ? WHERE id = ?"
                    );
                    $qr_stmt->bind_param('ssi', $qr_token, $qr_now, $new_student_db_id);
                    $qr_stmt->execute();
                    $qr_stmt->close();
                }
                echo json_encode(['success' => true, 'message' => 'Student added successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to add student: ' . $stmt->error]);
            }
            $stmt->close();
        }
        elseif ($action === 'update') {
            $id          = intval($_POST['id'] ?? 0);
            $student_id  = trim((string) ($_POST['student_id']  ?? ''));
            $first_name  = trim((string) ($_POST['first_name']  ?? ''));
            $last_name   = trim((string) ($_POST['last_name']   ?? ''));
            $class       = trim((string) ($_POST['class']       ?? ''));
            $section     = trim((string) ($_POST['section']     ?? ''));
            $parent_name = trim((string) ($_POST['parent_name'] ?? ''));
            $phone       = trim((string) ($_POST['phone']       ?? ''));
            $email       = trim((string) ($_POST['email']       ?? ''));
            $address     = trim((string) ($_POST['address']     ?? ''));
            $status      = trim((string) ($_POST['status']      ?? 'active'));

            $stmt = $conn->prepare("UPDATE students SET student_id = ?, first_name = ?, last_name = ?, class = ?, section = ?, parent_name = ?, phone = ?, email = ?, address = ?, status = ? WHERE id = ?");
            $stmt->bind_param("ssssssssssi", $student_id, $first_name, $last_name, $class, $section, $parent_name, $phone, $email, $address, $status, $id);

            if ($stmt->execute()) {
                echo json_encode(['success' => true, 'message' => 'Student updated successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to update student: ' . $stmt->error]);
            }
            $stmt->close();
        }
        elseif ($action === 'delete') {
            $id = intval($_GET['id'] ?? 0);
            
            $stmt = $conn->prepare("DELETE FROM students WHERE id = ?");
            $stmt->bind_param("i", $id);

            if ($stmt->execute()) {
                echo json_encode(['success' => true, 'message' => 'Student deleted successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to delete student: ' . $stmt->error]);
            }
            $stmt->close();
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
    }
    
    $conn->close();
    exit;
}

// Handle HTML responses for edit/view
if (in_array($action, ['edit', 'view'])) {
    header('Content-Type: text/html; charset=utf-8');
    $conn = getDBConnection();
    
    if (!$conn) {
        echo '<p>Database connection failed</p>';
        exit;
    }
    
    $id = intval($_GET['id'] ?? 0);
    $result = $conn->query("SELECT * FROM students WHERE id = $id");
    $student = $result ? $result->fetch_assoc() : null;

    // Load active classes; also include student's current class if not active
    $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'];
    }
    if (!empty($student['class']) && !in_array($student['class'], $classes_list)) {
        $classes_list[] = $student['class'];
        sort($classes_list);
    }

    if ($student) {
       if ($action === 'view') {
    ?>
    <div class="container-fluid">
        <!-- Student Photo & Basic Info -->
        <div class="row mb-4">
            <div class="col-md-3 text-center">
                <?php if (!empty($student['photo_path'])): ?>
                    <img src="./<?php echo $student['photo_path']; ?>" class="img-fluid rounded border" style="height: 150px; width: 520px;" alt="Student Photo">
                <?php else: ?>
                    <div class="bg-light p-4 text-center rounded">
                        <i class="fas fa-user-graduate fa-4x text-muted"></i>
                         
                        <p class="mt-2 text-muted">No Photo</p>
                    </div>
                <?php endif; ?>
            </div>
            <div class="col-md-9">
                <h4><?php echo safeHtml($student['first_name'] . ' ' . $student['last_name']); ?></h4>
                <p><strong>Student ID:</strong> <?php echo safeHtml($student['student_id']); ?> |
                   <strong>Status:</strong> <span class="badge badge-<?php echo $student['status'] === 'active' ? 'success' : 'danger'; ?>"><?php echo ucfirst($student['status']); ?></span></p>
                <a href="../admin/print_student_id.php?id=<?php echo (int)$student['id']; ?>"
                   target="_blank" class="btn btn-sm btn-outline-primary mt-1">
                    <i class="fas fa-id-card me-1"></i>Print ID Card
                </a>
            </div>
        </div>
        
        <!-- Personal Information -->
        <div class="card mb-3">
            <div class="card-header bg-primary text-white">
                <h6 class="mb-0"><i class="fas fa-user me-2"></i>Personal Information</h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4 mb-2"><strong>First Name:</strong> <?php echo safeHtml($student['first_name'] ?: '-'); ?></div>
                    <div class="col-md-4 mb-2"><strong>Last Name:</strong> <?php echo safeHtml($student['last_name'] ?: '-'); ?></div>
                    <div class="col-md-4 mb-2"><strong>Sex:</strong> <?php echo safeHtml($student['sex'] ?: '-'); ?></div>
                    <div class="col-md-4 mb-2"><strong>Date of Birth:</strong> <?php echo !empty($student['date_of_birth']) ? date('d M Y', strtotime($student['date_of_birth'])) : '-'; ?></div>
                    <div class="col-md-4 mb-2"><strong>Place of Birth:</strong> <?php echo safeHtml($student['place_of_birth'] ?: '-'); ?></div>
                    <div class="col-md-4 mb-2"><strong>Nationality:</strong> <?php echo safeHtml($student['nationality'] ?: '-'); ?></div>
                    <div class="col-md-4 mb-2"><strong>House No.:</strong> <?php echo safeHtml($student['house_no'] ?: '-'); ?></div>
                    <div class="col-md-4 mb-2"><strong>Class:</strong> <?php echo safeHtml($student['class'] ?: '-'); ?></div>
                    <div class="col-md-4 mb-2"><strong>Section:</strong> <?php echo safeHtml($student['section'] ?: '-'); ?></div>
                    <div class="col-md-4 mb-2"><strong>Religion:</strong> <?php echo safeHtml($student['religion'] ?: '-'); ?></div>
                    <div class="col-md-4 mb-2"><strong>Parents Live Together:</strong> <?php echo safeHtml($student['parents_live_together'] ?: '-'); ?></div>
                </div>
            </div>
        </div>
        
        <!-- Father's Information -->
        <div class="card mb-3">
            <div class="card-header bg-info text-white">
                <h6 class="mb-0"><i class="fas fa-male me-2"></i>Father's Information</h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6 mb-2"><strong>Name:</strong> <?php echo safeHtml($student['father_name'] ?: '-'); ?></div>
                    <div class="col-md-6 mb-2"><strong>Occupation:</strong> <?php echo safeHtml($student['father_occupation'] ?: '-'); ?></div>
                    <div class="col-md-6 mb-2"><strong>Address:</strong> <?php echo safeHtml($student['father_address'] ?: '-'); ?></div>
                    <div class="col-md-6 mb-2"><strong>Phone:</strong> <?php echo safeHtml($student['father_phone'] ?: '-'); ?></div>
                </div>
            </div>
        </div>
        
        <!-- Mother's Information -->
        <div class="card mb-3">
            <div class="card-header bg-info text-white">
                <h6 class="mb-0"><i class="fas fa-female me-2"></i>Mother's Information</h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6 mb-2"><strong>Name:</strong> <?php echo safeHtml($student['mother_name'] ?: '-'); ?></div>
                    <div class="col-md-6 mb-2"><strong>Occupation:</strong> <?php echo safeHtml($student['mother_occupation'] ?: '-'); ?></div>
                    <div class="col-md-6 mb-2"><strong>Address:</strong> <?php echo safeHtml($student['mother_address'] ?: '-'); ?></div>
                    <div class="col-md-6 mb-2"><strong>Phone:</strong> <?php echo safeHtml($student['mother_phone'] ?: '-'); ?></div>
                </div>
            </div>
        </div>
        
        <!-- Guardian Information (if applicable) -->
        <?php if (!empty($student['guardian_relationship'])): ?>
        <div class="card mb-3">
            <div class="card-header bg-secondary text-white">
                <h6 class="mb-0"><i class="fas fa-user-friends me-2"></i>Guardian Information</h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-12 mb-2"><strong>Relationship to Child:</strong> <?php echo safeHtml($student['guardian_relationship']); ?></div>
                </div>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Medical & Languages -->
        <div class="card mb-3">
            <div class="card-header bg-warning text-dark">
                <h6 class="mb-0"><i class="fas fa-notes-medical me-2"></i>Medical & Languages</h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6 mb-2"><strong>Has Handicap/Allergy:</strong> <?php echo safeHtml($student['has_handicap'] ?: '-'); ?></div>
                    <?php if (!empty($student['handicap_description'])): ?>
                    <div class="col-md-12 mb-2"><strong>Description:</strong> <?php echo safeHtml($student['handicap_description']); ?></div>
                    <?php endif; ?>
                    <div class="col-md-12 mb-2"><strong>Languages Spoken:</strong> <?php echo safeHtml($student['languages_spoken'] ?: '-'); ?></div>
                </div>
            </div>
        </div>
        
        <!-- School History -->
        <div class="card mb-3">
            <div class="card-header bg-success text-white">
                <h6 class="mb-0"><i class="fas fa-school me-2"></i>School History</h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6 mb-2"><strong>Last School Attended:</strong> <?php echo safeHtml($student['last_school'] ?: '-'); ?></div>
                    <div class="col-md-6 mb-2"><strong>Last Class:</strong> <?php echo safeHtml($student['last_class'] ?: '-'); ?></div>
                </div>
            </div>
        </div>
        
        <!-- Emergency Contact -->
        <div class="card mb-3">
            <div class="card-header bg-danger text-white">
                <h6 class="mb-0"><i class="fas fa-phone-alt me-2"></i>Emergency Contact</h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4 mb-2"><strong>Name:</strong> <?php echo safeHtml($student['emergency_contact_name'] ?: '-'); ?></div>
                    <div class="col-md-4 mb-2"><strong>Address:</strong> <?php echo safeHtml($student['emergency_contact_address'] ?: '-'); ?></div>
                    <div class="col-md-4 mb-2"><strong>Phone:</strong> <?php echo safeHtml($student['emergency_contact_phone'] ?: '-'); ?></div>
                </div>
            </div>
        </div>
        
        <!-- Signature -->
        <?php if (!empty($student['signature_path']) && file_exists($student['signature_path'])): ?>
        <div class="card mb-3">
            <div class="card-header bg-dark text-white">
                <h6 class="mb-0"><i class="fas fa-signature me-2"></i>Signature</h6>
            </div>
            <div class="card-body text-center">
                <img src="<?php echo $student['signature_path']; ?>" style="max-height: 100px;" alt="Signature">
            </div>
        </div>
        <?php endif; ?>
        
        <!-- System Information -->
        <div class="card mb-3">
            <div class="card-header bg-secondary text-white">
                <h6 class="mb-0"><i class="fas fa-clock me-2"></i>System Information</h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6 mb-2"><strong>Created At:</strong> <?php echo !empty($student['created_at']) ? date('d M Y H:i', strtotime($student['created_at'])) : '-'; ?></div>
                </div>
            </div>
        </div>
    </div>
    <?php
}else {
    // Edit mode - show all fields in tabs
    ?>
    <input type="hidden" name="id" value="<?php echo $student['id']; ?>">
    
    <!-- Nav tabs -->
    <ul class="nav nav-tabs" id="editStudentTabs" role="tablist">
        <li class="nav-item"><div class="nav-link active" data-bs-toggle="tab" data-bs-target="#edit-personal">Personal Info</div></li>
        <li class="nav-item"><div class="nav-link" data-bs-toggle="tab" data-bs-target="#edit-parents">Parents/Guardian</div></li>
        <li class="nav-item"><div class="nav-link" data-bs-toggle="tab" data-bs-target="#edit-medical">Medical & Languages</div></li>
        <li class="nav-item"><div class="nav-link" data-bs-toggle="tab" data-bs-target="#edit-school">School History</div></li>
        <li class="nav-item"><div class="nav-link" data-bs-toggle="tab" data-bs-target="#edit-emergency">Emergency</div></li>
        <li class="nav-item"><div class="nav-link" data-bs-toggle="tab" data-bs-target="#edit-media">Photo & Signature</div></li>
    </ul>
    
    <!-- Tab panes -->
    <div class="tab-content mt-3">
        <!-- Personal Info Tab -->
        <div class="tab-pane fade show active" id="edit-personal">
            <div class="row">
                <div class="col-md-4 mb-3">
                    <label class="form-label">Student ID *</label>
                    <input type="text" class="form-control" name="student_id" value="<?php echo safeHtml($student['student_id']); ?>" readonly class="form-control-plaintext">
                    <small class="text-muted">Student ID cannot be changed</small>
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">First Name *</label>
                    <input type="text" class="form-control" name="first_name" value="<?php echo safeHtml($student['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" value="<?php echo safeHtml($student['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" <?php echo ($student['sex'] == 'Male') ? 'selected' : ''; ?>>Male</option>
                        <option value="Female" <?php echo ($student['sex'] == 'Female') ? 'selected' : ''; ?>>Female</option>
                        <option value="Other" <?php echo ($student['sex'] == 'Other') ? 'selected' : ''; ?>>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" value="<?php echo safeHtml($student['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" value="<?php echo safeHtml($student['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" value="<?php echo safeHtml($student['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" value="<?php echo safeHtml($student['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="<?php echo htmlspecialchars($cls); ?>" <?php echo ($student['class'] == $cls) ? 'selected' : ''; ?>><?php echo 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" value="<?php echo safeHtml($student['section']); ?>">
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">Religious Denomination</label>
                    <input type="text" class="form-control" name="religion" value="<?php echo safeHtml($student['religion']); ?>">
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">Parents Live Together?</label>
                    <select class="form-select" name="parents_live_together">
                        <option value="">Select</option>
                        <option value="Yes" <?php echo ($student['parents_live_together'] == 'Yes') ? 'selected' : ''; ?>>Yes</option>
                        <option value="No" <?php echo ($student['parents_live_together'] == 'No') ? 'selected' : ''; ?>>No</option>
                    </select>
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">Status</label>
                    <select class="form-select" name="status">
                        <option value="active" <?php echo ($student['status'] == 'active') ? 'selected' : ''; ?>>Active</option>
                        <option value="inactive" <?php echo ($student['status'] == 'inactive') ? 'selected' : ''; ?>>Inactive</option>
                    </select>
                </div>
            </div>
        </div>
        
        <!-- Parents/Guardian Tab -->
        <div class="tab-pane fade" id="edit-parents">
            <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" value="<?php echo safeHtml($student['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" value="<?php echo safeHtml($student['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"><?php echo safeHtml($student['father_address']); ?></textarea>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">Phone *</label>
                    <input type="tel" class="form-control" name="father_phone" value="<?php echo safeHtml($student['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" value="<?php echo safeHtml($student['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" value="<?php echo safeHtml($student['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"><?php echo safeHtml($student['mother_address']); ?></textarea>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">Phone *</label>
                    <input type="tel" class="form-control" name="mother_phone" value="<?php echo safeHtml($student['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" value="<?php echo safeHtml($student['guardian_relationship']); ?>">
                </div>
            </div>
            
            <!-- Legacy fields (kept for backward compatibility) -->
            <hr>
            <h6>Legacy Contact Information</h6>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">Parent Name (Legacy)</label>
                    <input type="text" class="form-control" name="parent_name" value="<?php echo safeHtml($student['parent_name']); ?>">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">Phone (Legacy) *</label>
                    <input type="tel" class="form-control" name="phone" value="<?php echo safeHtml($student['phone']); ?>" required>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">Email</label>
                    <input type="email" class="form-control" name="email" value="<?php echo safeHtml($student['email']); ?>">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">Address</label>
                    <textarea class="form-control" name="address" rows="2"><?php echo safeHtml($student['address']); ?></textarea>
                </div>
            </div>
        </div>
        
        <!-- Medical & Languages Tab -->
        <div class="tab-pane fade" id="edit-medical">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">Has Handicap/Allergy?</label>
                    <select class="form-select" name="has_handicap" id="edit_has_handicap">
                        <option value="">Select</option>
                        <option value="Yes" <?php echo ($student['has_handicap'] == 'Yes') ? 'selected' : ''; ?>>Yes</option>
                        <option value="No" <?php echo ($student['has_handicap'] == 'No') ? 'selected' : ''; ?>>No</option>
                    </select>
                </div>
                <div class="col-md-6 mb-3" id="edit_handicap_desc_group" style="<?php echo ($student['has_handicap'] == 'Yes') ? 'display:block;' : 'display:none;'; ?>">
                    <label class="form-label">Description</label>
                    <textarea class="form-control" name="handicap_description" rows="2"><?php echo safeHtml($student['handicap_description']); ?></textarea>
                </div>
                <div class="col-md-12 mb-3">
                    <label class="form-label">Languages Spoken</label>
                    <input type="text" class="form-control" name="languages_spoken" value="<?php echo safeHtml($student['languages_spoken']); ?>" placeholder="e.g., English, Twi">
                </div>
            </div>
        </div>
        
        <!-- School History Tab -->
        <div class="tab-pane fade" id="edit-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" value="<?php echo safeHtml($student['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" value="<?php echo safeHtml($student['last_class']); ?>">
                </div>
            </div>
        </div>
        
        <!-- Emergency Contact Tab -->
        <div class="tab-pane fade" id="edit-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" value="<?php echo safeHtml($student['emergency_contact_name']); ?>" required>
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">Address *</label>
                    <input type="text" class="form-control" name="emergency_contact_address" value="<?php echo safeHtml($student['emergency_contact_address']); ?>" required>
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">Phone *</label>
                    <input type="tel" class="form-control" name="emergency_contact_phone" value="<?php echo safeHtml($student['emergency_contact_phone']); ?>" required>
                </div>
            </div>
        </div>
        
        <!-- Photo & Signature Tab -->
        <div class="tab-pane fade" id="edit-media">
            <div class="row">
                <!-- Current Photo Preview -->
                <?php if (!empty($student['photo_path']) && file_exists($student['photo_path'])): ?>
                <div class="col-md-6 mb-3">
                    <div class="card">
                        <div class="card-header bg-light">
                            <h6 class="mb-0">Current Photo</h6>
                        </div>
                        <div class="card-body text-center">
                            <img src="<?php echo $student['photo_path']; ?>" style="max-height: 150px;" class="img-fluid border rounded" alt="Current Photo">
                            <div class="form-check mt-2">
                                <input class="form-check-input" type="checkbox" name="remove_photo" id="remove_photo">
                                <label class="form-check-label" for="remove_photo">Remove current photo</label>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- New Photo Upload -->
                <div class="col-md-6 mb-3">
                    <div class="card">
                        <div class="card-header bg-light">
                            <h6 class="mb-0">Upload New Photo</h6>
                        </div>
                        <div class="card-body">
                            <div id="edit-webcam-container" class="mb-3 text-center"></div>
                            <div id="edit-photo-preview" class="mb-3 text-center"></div>
                            <div class="d-grid gap-2 mb-3">
                                <button type="button" class="btn btn-primary" onclick="captureEditPhoto()">
                                    <i class="fas fa-camera me-2"></i>Capture New 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 File</label>
                                <input type="file" class="form-control" id="edit-photo-file" name="photo" accept="image/*">
                            </div>
                            <input type="hidden" name="photo_data" id="edit_photo_data">
                        </div>
                    </div>
                </div>
                
                <!-- Current Signature Preview -->
                <?php if (!empty($student['signature_path']) && file_exists($student['signature_path'])): ?>
                <div class="col-md-6 mb-3">
                    <div class="card">
                        <div class="card-header bg-light">
                            <h6 class="mb-0">Current Signature</h6>
                        </div>
                        <div class="card-body text-center">
                            <img src="<?php echo $student['signature_path']; ?>" style="max-height: 100px;" class="img-fluid border rounded" alt="Current Signature">
                            <div class="form-check mt-2">
                                <input class="form-check-input" type="checkbox" name="remove_signature" id="remove_signature">
                                <label class="form-check-label" for="remove_signature">Remove current signature</label>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- New Signature Pad -->
                <div class="col-md-6 mb-3">
                    <div class="card">
                        <div class="card-header bg-light">
                            <h6 class="mb-0">New Signature</h6>
                        </div>
                        <div class="card-body">
                            <canvas id="edit-signature-pad" class="border rounded w-100" width="300" height="150"></canvas>
                            <div id="edit-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="clearEditSignature()">
                                        <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="saveEditSignature()">
                                        <i class="fas fa-save me-2"></i>Save
                                    </button>
                                </div>
                            </div>
                            <input type="hidden" name="signature_data" id="edit_signature_data">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        // Show/hide handicap description for edit form
        document.getElementById('edit_has_handicap').addEventListener('change', function() {
            document.getElementById('edit_handicap_desc_group').style.display = this.value === 'Yes' ? 'block' : 'none';
        });
        
        // Signature pad for edit form
        let editCanvas = document.getElementById('edit-signature-pad');
        let editSignaturePad = new SignaturePad(editCanvas, {
            backgroundColor: 'rgb(255,255,255)'
        });
        
        function clearEditSignature() {
            editSignaturePad.clear();
            document.getElementById('edit_signature_data').value = '';
        }
        
        function saveEditSignature() {
            if (editSignaturePad.isEmpty()) {
                alert('Please provide a signature.');
                return;
            }
            const dataURL = editSignaturePad.toDataURL();
            document.getElementById('edit_signature_data').value = dataURL;
            
            // Show preview
            const previewHtml = '<img src="' + dataURL + '" style="max-width:100%; max-height:100px; border:1px solid #ddd; padding:5px;">';
            document.getElementById('edit-signature-preview').innerHTML = previewHtml;
            
            alert('Signature captured!');
        }
        
        // Webcam for edit form
        function captureEditPhoto() {
            Webcam.snap(function(data_uri) {
                document.getElementById('edit_photo_data').value = data_uri;
                
                // Show preview
                const previewHtml = '<img src="' + data_uri + '" style="max-width:100%; max-height:200px; border:1px solid #ddd; padding:5px;">';
                document.getElementById('edit-photo-preview').innerHTML = previewHtml;
                
                alert('Photo captured!');
            });
        }
        
        // Initialize webcam when edit modal is shown
        $('#editStudentModal').on('shown.bs.modal', function() {
            Webcam.set({
                width: 320,
                height: 240,
                image_format: 'jpeg',
                jpeg_quality: 90
            });
            Webcam.attach('#edit-webcam-container');
        });
        
        // Stop webcam when edit modal is hidden
        $('#editStudentModal').on('hidden.bs.modal', function() {
            Webcam.reset();
        });
        
        // Handle file upload preview
        document.getElementById('edit-photo-file').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    document.getElementById('edit-photo-preview').innerHTML = '<img src="' + e.target.result + '" style="max-width:100%; max-height:200px; border:1px solid #ddd; padding:5px;">';
                };
                reader.readAsDataURL(file);
            }
        });
    </script>
    <?php
}
    } else {
        echo '<p>Student not found</p>';
    }
    
    $conn->close();
    exit;
}

// Default response
echo json_encode(['success' => false, 'message' => 'Invalid action']);
?>