<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
include "../include/config.php";
$userlogin = $_SESSION['studentid'];
$intake = $_SESSION['intake'];
$pro = $_SESSION['program'];

// Generate CSRF token if not exists
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Debug: Show CSRF token (remove in production)
error_log("CSRF Token for student " . $userlogin . ": " . $_SESSION['csrf_token']);

if (isset($_SESSION['studentid'])) {
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Student Profile</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600;700&family=Source+Sans+Pro:wght@300;400;600&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --primary-color: var(--primary);
            --secondary-color: #2c3e50;
            --accent-color: #ff8a65;
            --light-color: #f8f9fa;
            --dark-color: #343a40;
        }
        
        body {
            font-family: 'Montserrat', sans-serif;
            background-color: #f5f7fa;
            color: #333;
            padding: 0;
            margin: 0;
        }
        
        .navbar-custom {
            background-color: var(--secondary-color);
        }
        
        .profile-card {
            border-radius: 12px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            border: none;
            margin-bottom: 20px;
            overflow: hidden;
        }
        
        .profile-header {
            background: var(--primary-color);
            color: white;
            padding: 30px 20px;
            text-align: center;
        }
        
        .profile-content {
            padding: 25px;
            background: #fff;
        }
        
        .info-item {
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eaeaea;
        }
        
        .info-item:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }
        
        .info-label {
            font-weight: 600;
            color: var(--secondary-color);
            margin-bottom: 5px;
            font-size: 0.9rem;
        }
        
        .status-badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 500;
            font-size: 0.85rem;
            display: inline-block;
        }
        
        .btn-edit {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
            color: white;
            border-radius: 8px;
            padding: 10px 25px;
            font-weight: 500;
            transition: all 0.3s;
        }
        
        .btn-edit:hover {
            background-color: #1a6b4f;
            border-color: #1a6b4f;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            color: white;
        }
        
        /* Modal customization */
        .modal-content {
            border-radius: 12px;
            border: none;
            box-shadow: 0 5px 25px rgba(0,0,0,0.15);
        }
        
        .modal-header {
            background: var(--primary-color);
            color: white;
            border-radius: 12px 12px 0 0;
            padding: 20px;
        }
        
        .form-control, .form-select {
            border-radius: 8px;
            padding: 12px 15px;
            border: 1px solid #ddd;
            transition: all 0.3s;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(35, 134, 101, 0.2);
        }
        
        .profile-image-container img {
            width: 150px;
            height: 150px;
            object-fit: cover;
            border: 4px solid white;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            transition: transform 0.3s ease;
        }
        
        .profile-image-container img:hover {
            transform: scale(1.05);
        }
        
        .profile-image-placeholder {
            width: 150px;
            height: 150px;
            background: rgba(255,255,255,0.1);
            border: 4px solid white;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        
        /* Success/Error Messages */
        .alert-message {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
            min-width: 300px;
            animation: slideIn 0.3s ease-out;
        }
        
        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
        
        /* CSRF warning */
        .csrf-warning {
            font-size: 0.8rem;
            color: #dc3545;
            display: none;
        }
        
        /* Responsive adjustments */
        @media (max-width: 768px) {
            .profile-header {
                padding: 20px 15px;
            }
            
            .profile-content {
                padding: 15px;
            }
            
            .profile-image-container img {
                width: 120px;
                height: 120px;
            }
            
            .btn-edit {
                width: 100%;
                margin-top: 10px;
            }
        }
    </style>
</head>
<body>
    <?php include "../include/nav.php"; ?>
    
    <!-- Success/Error Messages -->
    <?php if(isset($_SESSION['success'])): ?>
    <div class="alert alert-success alert-message alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle me-2"></i><?php echo $_SESSION['success']; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        <?php unset($_SESSION['success']); ?>
    </div>
    <?php endif; ?>
    
    <?php if(isset($_SESSION['error'])): ?>
    <div class="alert alert-danger alert-message alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle me-2"></i><?php echo $_SESSION['error']; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        <?php unset($_SESSION['error']); ?>
    </div>
    <?php endif; ?>

    <div class="content" style="padding:15px">
        <div class="container">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h4 style="color: var(--primary-color);">
                    <i class="fas fa-user me-2"></i>My Profile
                </h4>
                <button type="button" class="btn btn-edit" data-bs-toggle="modal" data-bs-target="#editProfileModal">
                    <i class="fas fa-edit me-2"></i>Edit Profile
                </button>
            </div>

            <?php
            $query = mysqli_query($conn, "SELECT * FROM students WHERE studentid='$userlogin' LIMIT 1");
            
            if ($row = mysqli_fetch_assoc($query)) {
                $currentYear = date("Y");
                $yearOfStudy = "";
                
                if ($currentYear == $row['start_year']) {
                    $yearOfStudy = "First Year";
                } elseif ($currentYear == $row['start_year'] + 1) {
                    $yearOfStudy = "Second Year";
                } elseif ($currentYear == $row['start_year'] + 2) {
                    $yearOfStudy = "Third Year";
                } elseif ($currentYear == $row['start_year'] + 3) {
                    $yearOfStudy = "Fourth Year";
                } else {
                    $yearOfStudy = "Completed / Other";
                }
                
                $status_class = $row['status'] == 'active' ? 'bg-success' : 'bg-danger';
                $boarding_class = $row['boarding_status'] == 'Resident' ? 'bg-info' : 'bg-secondary';
            ?>
            
            <div class="profile-card">
                <div class="profile-header">
                    <div class="d-flex flex-column align-items-center">
                        <?php if(!empty($row['image']) && filter_var($row['image'], FILTER_VALIDATE_URL)): ?>
                        <div class="profile-image-container mb-3">
                            <img src="<?php echo htmlspecialchars($row['image']); ?>" 
                                 alt="<?php echo htmlspecialchars($row['studentname']); ?>" 
                                 class="rounded-circle">
                        </div>
                        <?php else: ?>
                        <div class="profile-image-placeholder rounded-circle mb-3 d-flex align-items-center justify-content-center">
                            <i class="fas fa-user text-white" style="font-size: 60px;"></i>
                        </div>
                        <?php endif; ?>
                        <h2 class="mb-2"><?php echo htmlspecialchars($row['studentname']); ?></h2>
                        <p class="mb-1"><?php echo htmlspecialchars($row['program']); ?></p>
                        <p class="mb-0">Intake: <?php echo htmlspecialchars($row['intake']); ?> (<?php echo $row['start_year']." - ".$row['end_year']; ?>)</p>
                    </div>
                </div>
                
                <div class="profile-content">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="info-item">
                                <div class="info-label">Student ID</div>
                                <div><i class="fas fa-id-card text-primary me-2"></i><?php echo htmlspecialchars($row['studentid']); ?></div>
                            </div>
                            
                            <div class="info-item">
                                <div class="info-label">Full Name</div>
                                <div><i class="fas fa-user text-primary me-2"></i><?php echo htmlspecialchars($row['studentname']); ?></div>
                            </div>
                            
                            <div class="info-item">
                                <div class="info-label">Program</div>
                                <div><i class="fas fa-graduation-cap text-primary me-2"></i><?php echo htmlspecialchars($row['program']); ?></div>
                            </div>
                            
                            <div class="info-item">
                                <div class="info-label">Intake</div>
                                <div><i class="fas fa-calendar-alt text-primary me-2"></i><?php echo htmlspecialchars($row['intake']); ?></div>
                            </div>
                            
                            <div class="info-item">
                                <div class="info-label">Study Period</div>
                                <div><i class="fas fa-clock text-primary me-2"></i><?php echo $row['start_year']; ?> - <?php echo $row['end_year']; ?></div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="info-item">
                                <div class="info-label">Year of Study</div>
                                <div><i class="fas fa-university text-primary me-2"></i><?php echo $yearOfStudy; ?></div>
                            </div>
                            
                            <div class="info-item">
                                <div class="info-label">Gender</div>
                                <div><i class="fas fa-venus-mars text-primary me-2"></i><?php echo htmlspecialchars($row['gender']); ?></div>
                            </div>
                            
                            <div class="info-item">
                                <div class="info-label">Contact Information</div>
                                <div>
                                    <div><i class="fas fa-phone text-primary me-2"></i> <?php echo htmlspecialchars($row['mobile']); ?></div>
                                    <div><i class="fas fa-envelope text-primary me-2"></i> <?php echo htmlspecialchars($row['email']); ?></div>
                                </div>
                            </div>
                            
                            <div class="info-item">
                                <div class="info-label">Status</div>
                                <div>
                                    <span class="status-badge <?php echo $status_class; ?>">
                                        <i class="fas fa-circle me-1" style="font-size: 8px;"></i>
                                        <?php echo ucfirst($row['status']); ?>
                                    </span>
                                </div>
                            </div>
                            
                            <div class="info-item">
                                <div class="info-label">Boarding Information</div>
                                <div>
                                    <span class="status-badge <?php echo $boarding_class; ?> me-2">
                                        <?php echo $row['boarding_status']; ?>
                                    </span>
                                    <?php if (!empty($row['hostel_name'])): ?>
                                    <?php echo htmlspecialchars($row['hostel_name']); ?>
                                    <?php if (!empty($row['room_number'])): ?>
                                    (Room <?php echo htmlspecialchars($row['room_number']); ?>)
                                    <?php endif; ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Parent Information Section -->
                    <div class="row mt-4">
                        <div class="col-12">
                            <h5 class="mb-3" style="color: var(--primary-color); border-bottom: 2px solid var(--primary-color); padding-bottom: 8px;">
                                <i class="fas fa-users me-2"></i>Parent/Guardian Information
                            </h5>
                        </div>
                        <div class="col-md-6">
                            <div class="info-item">
                                <div class="info-label">Parent Name</div>
                                <div><i class="fas fa-user-friends text-primary me-2"></i><?php echo htmlspecialchars($row['parent_name']); ?></div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="info-item">
                                <div class="info-label">Relationship</div>
                                <div><i class="fas fa-heart text-primary me-2"></i><?php echo htmlspecialchars($row['parent_relation']); ?></div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="info-item">
                                <div class="info-label">Parent Mobile</div>
                                <div><i class="fas fa-phone-alt text-primary me-2"></i><?php echo htmlspecialchars($row['parent_mobile']); ?></div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="info-item">
                                <div class="info-label">Parent Email</div>
                                <div><i class="fas fa-envelope-open-text text-primary me-2"></i><?php echo htmlspecialchars($row['parent_email']); ?></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <?php
            } else {
                echo '<div class="alert alert-danger">No profile found.</div>';
            }
            ?>  
        </div>
    </div>

    <!-- Edit Profile Modal -->
    <div style="z-index:9999;" class="modal fade" id="editProfileModal" tabindex="-1" aria-labelledby="editProfileModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editProfileModalLabel">
                        <i class="fas fa-edit me-2"></i>Edit Profile Information
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <?php
                    $query = mysqli_query($conn, "SELECT * FROM students WHERE studentid='$userlogin' LIMIT 1");
                    if ($student = mysqli_fetch_assoc($query)) {
                    ?>
<form action="update_profile.php" method="post" enctype="multipart/form-data">
                        <!-- CSRF Token - ADD THIS LINE -->
                        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                        <input type="hidden" name="id" value="<?php echo $student['id']; ?>">
                        
                        <div class="row mb-4">
                            <div class="col-12 text-center">
                                <?php if(!empty($student['image']) && filter_var($student['image'], FILTER_VALIDATE_URL)): ?>
                                <img src="<?php echo htmlspecialchars($student['image']); ?>" 
                                     alt="Current Profile" 
                                     class="rounded-circle mb-3"
                                     style="width: 100px; height: 100px; object-fit: cover; border: 3px solid var(--primary-color);">
                                <?php else: ?>
                                <div class="rounded-circle bg-light d-inline-flex align-items-center justify-content-center mb-3"
                                     style="width: 100px; height: 100px; border: 3px solid var(--primary-color);">
                                    <i class="fas fa-user text-muted" style="font-size: 40px;"></i>
                                </div>
                                <?php endif; ?>
                                <h6>Profile Picture</h6>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Student ID</label>
                                <input type="text" class="form-control" value="<?php echo htmlspecialchars($student['studentid']); ?>" disabled>
                                <small class="text-muted">Student ID cannot be changed</small>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Full Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="studentname" value="<?php echo htmlspecialchars($student['studentname']); ?>" required>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Program</label>
                                <input type="text" class="form-control" value="<?php echo htmlspecialchars($student['program']); ?>" disabled>
                                <small class="text-muted">Program cannot be changed</small>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Intake</label>
                                <input type="text" class="form-control" value="<?php echo htmlspecialchars($student['intake']); ?>" disabled>
                                <small class="text-muted">Intake cannot be changed</small>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Email Address <span class="text-danger">*</span></label>
                                <input type="email" class="form-control" name="email" value="<?php echo htmlspecialchars($student['email']); ?>" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Mobile Number <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="mobile" value="<?php echo htmlspecialchars($student['mobile']); ?>" required>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Gender <span class="text-danger">*</span></label>
                                <select name="gender" class="form-select" required>
                                    <option value="">Select Gender</option>
                                    <option value="Male" <?php echo $student['gender'] == 'Male' ? 'selected' : ''; ?>>Male</option>
                                    <option value="Female" <?php echo $student['gender'] == 'Female' ? 'selected' : ''; ?>>Female</option>
                                    <option value="Other" <?php echo $student['gender'] == 'Other' ? 'selected' : ''; ?>>Other</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Profile Image</label>
                                <input type="file" class="form-control" name="image" accept="image/*" id="imageUpload">
                                <small class="text-muted">Max size: 2MB. Allowed: JPG, PNG, GIF, WebP</small>
                                <div class="mt-2" id="imagePreview"></div>
                            </div>
                        </div>
                        
                        <h5 class="mt-4 mb-3" style="color: var(--primary-color); border-bottom: 1px solid #eee; padding-bottom: 8px;">
                            <i class="fas fa-users me-2"></i>Parent/Guardian Information
                        </h5>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Parent Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="parent_name" value="<?php echo htmlspecialchars($student['parent_name']); ?>" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Parent Relation <span class="text-danger">*</span></label>
                                <select name="parent_relation" class="form-select" required>
                                    <option value="">Select Relation</option>
                                    <option value="Father" <?php echo $student['parent_relation'] == 'Father' ? 'selected' : ''; ?>>Father</option>
                                    <option value="Mother" <?php echo $student['parent_relation'] == 'Mother' ? 'selected' : ''; ?>>Mother</option>
                                    <option value="Guardian" <?php echo $student['parent_relation'] == 'Guardian' ? 'selected' : ''; ?>>Guardian</option>
                                    <option value="Other" <?php echo $student['parent_relation'] == 'Other' ? 'selected' : ''; ?>>Other</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Parent Mobile <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="parent_mobile" value="<?php echo htmlspecialchars($student['parent_mobile']); ?>" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Parent Email</label>
                                <input type="email" class="form-control" name="parent_email" value="<?php echo htmlspecialchars($student['parent_email']); ?>">
                            </div>
                        </div>
                        
                        <h5 class="mt-4 mb-3" style="color: var(--primary-color); border-bottom: 1px solid #eee; padding-bottom: 8px;">
                            <i class="fas fa-home me-2"></i>Boarding Information
                        </h5>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Boarding Status</label>
                                <select name="boarding_status" class="form-select">
                                    <option value="">Select Status</option>
                                    <option value="Resident" <?php echo $student['boarding_status'] == 'Resident' ? 'selected' : ''; ?>>Resident</option>
                                    <option value="Day Scholar" <?php echo $student['boarding_status'] == 'Day Scholar' ? 'selected' : ''; ?>>Day Scholar</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Hostel Name</label>
                                <select name="hostel_name" class="form-select">
                                    <option value="">Select Hostel</option>
                                    <option value="University Hall" <?php echo $student['hostel_name'] == 'University Hall' ? 'selected' : ''; ?>>University Hall</option>
                                    <option value="Pioneer House" <?php echo $student['hostel_name'] == 'Pioneer House' ? 'selected' : ''; ?>>Pioneer House</option>
                                    <option value="Scholars Residence" <?php echo $student['hostel_name'] == 'Scholars Residence' ? 'selected' : ''; ?>>Scholars Residence</option>
                                    <option value="Campus Lodge" <?php echo $student['hostel_name'] == 'Campus Lodge' ? 'selected' : ''; ?>>Campus Lodge</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Room Number</label>
                                <input type="text" class="form-control" name="room_number" value="<?php echo htmlspecialchars($student['room_number']); ?>">
                            </div>
                        </div>
                        
                        <!-- CSRF Warning -->
                        <div class="alert alert-warning csrf-warning mb-3" id="csrfWarning">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            <strong>Security Warning:</strong> Your session token may have expired. Please refresh the page and try again.
                        </div>
                        
                        <div class="d-grid gap-2 d-md-flex justify-content-md-end mt-4">
                            <button type="button" class="btn btn-secondary me-md-2" data-bs-dismiss="modal">Cancel</button>
                            <button type="submit" name="updateprofile" class="btn btn-primary" id="submitBtn">
                                <i class="fas fa-save me-2"></i>Update Profile
                            </button>
                        </div>
                    </form>
                    <?php } ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS Bundle -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Auto-hide alerts after 5 seconds
        setTimeout(function() {
            const alerts = document.querySelectorAll('.alert-message');
            alerts.forEach(alert => {
                alert.style.transition = 'opacity 0.5s ease';
                alert.style.opacity = 0;
                setTimeout(() => alert.remove(), 500);
            });
        }, 5000);
        
        // Image preview functionality
        document.getElementById('imageUpload').addEventListener('change', function(e) {
            const file = e.target.files[0];
            const preview = document.getElementById('imagePreview');
            
            if (file) {
                // Check file size (max 2MB)
                if (file.size > 2 * 1024 * 1024) {
                    alert('File size must be less than 2MB');
                    e.target.value = '';
                    preview.innerHTML = '';
                    return;
                }
                
                // Check file type
                const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
                if (!validTypes.includes(file.type)) {
                    alert('Please select a valid image file (JPG, PNG, GIF, WebP)');
                    e.target.value = '';
                    preview.innerHTML = '';
                    return;
                }
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.innerHTML = `
                        <div class="alert alert-info p-2">
                            <div class="d-flex align-items-center">
                                <img src="${e.target.result}" alt="Preview" 
                                     style="width: 60px; height: 60px; object-fit: cover; border-radius: 5px; margin-right: 10px;">
                                <div>
                                    <strong>Selected:</strong> ${file.name}<br>
                                    <small>Size: ${(file.size / 1024).toFixed(2)} KB</small>
                                </div>
                            </div>
                        </div>
                    `;
                }
                reader.readAsDataURL(file);
            } else {
                preview.innerHTML = '';
            }
        });
        
        // Form validation
        document.getElementById('profileForm').addEventListener('submit', function(e) {
            const mobile = document.querySelector('input[name="mobile"]').value;
            const parentMobile = document.querySelector('input[name="parent_mobile"]').value;
            
            // Validate mobile numbers (basic validation)
            const mobileRegex = /^[\d\s\-\+\(\)]{10,15}$/;
            
            if (!mobileRegex.test(mobile)) {
                alert('Please enter a valid mobile number (10-15 digits)');
                e.preventDefault();
                return false;
            }
            
            if (parentMobile && !mobileRegex.test(parentMobile)) {
                alert('Please enter a valid parent mobile number (10-15 digits)');
                e.preventDefault();
                return false;
            }
            
            // Show loading state
            const submitBtn = document.getElementById('submitBtn');
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Updating...';
            submitBtn.disabled = true;
            
            // Check if form was open for too long (CSRF timeout)
            const csrfToken = document.querySelector('input[name="csrf_token"]').value;
            if (!csrfToken || csrfToken.length < 10) {
                document.getElementById('csrfWarning').style.display = 'block';
                e.preventDefault();
                return false;
            }
            
            return true;
        });
        
        // Refresh page when modal is opened to get fresh CSRF token
        document.getElementById('editProfileModal').addEventListener('show.bs.modal', function() {
            // Optional: You could refresh CSRF token via AJAX here
            console.log('Modal opened - CSRF Token:', document.querySelector('input[name="csrf_token"]').value);
        });
        
        // Handle modal close - reset form
        document.getElementById('editProfileModal').addEventListener('hidden.bs.modal', function() {
            document.getElementById('imagePreview').innerHTML = '';
            document.getElementById('csrfWarning').style.display = 'none';
        });
        
        // Debug: Show CSRF token in console (remove in production)
        console.log('CSRF Token for debugging:', '<?php echo $_SESSION['csrf_token']; ?>');
    </script>
    <br><br><br>
</body>
</html>
<?php
} else {
    header("location:../index.php");
}
?>