<?php
declare(strict_types=1);
$prefill_school_id = trim((string)($_GET['school_id'] ?? ''));

require_once __DIR__ . "/../config/db.php";
require_once __DIR__ . "/../config/auth.php";

require_login();
$u = current_user();
$uid = (int)($u['id'] ?? 0);
$rep_name = (string)($u['name'] ?? '');
$role = (string)($u['role'] ?? 'REP');

// Get assigned districts, blocks, GPs for REP
$assigned_dist_blocks_gps = [];
if ($role !== 'ADMIN') {
    $st = $pdo->prepare("
        SELECT DISTINCT
            b.district_id,
            b.id AS block_id,
            g.id AS gp_id,
            d.name AS district_name,
            b.name AS block_name,
            g.name AS gp_name
        FROM gp_assignments a
        JOIN gps g ON g.id = a.gp_id
        JOIN blocks b ON b.id = g.block_id
        LEFT JOIN districts d ON d.id = b.district_id
        WHERE a.user_id = ? AND a.status = 'ACTIVE'
        ORDER BY d.name, b.name, g.name
    ");
    $st->execute([$uid]);
    $assigned_dist_blocks_gps = $st->fetchAll(PDO::FETCH_ASSOC);
}

// Initialize session for multi-step form
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
if (!isset($_SESSION['visit_data'])) {
    $_SESSION['visit_data'] = [];
}

// Get school details if prefill ID exists
$school_details = null;
if ($prefill_school_id) {
    $st = $pdo->prepare("SELECT s.*, g.name as gp_name, b.name as block_name, d.name as district_name 
                        FROM schools s 
                        JOIN gps g ON g.id = s.gp_id
                        JOIN blocks b ON b.id = g.block_id
                        LEFT JOIN districts d ON d.id = b.district_id
                        WHERE s.id = ?");
    $st->execute([$prefill_school_id]);
    $school_details = $st->fetch(PDO::FETCH_ASSOC);
    
    if ($school_details) {
        $_SESSION['visit_data']['school_id'] = $prefill_school_id;
        $_SESSION['visit_data']['school_details'] = $school_details;
    }
}

$current_step = isset($_GET['step']) ? (int)$_GET['step'] : 1;
$success = "";
$error = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = (string)($_POST['csrf'] ?? '');
    if (!csrf_validate($token)) {
        $error = "Invalid request.";
    } else {
        $step = (int)($_POST['step'] ?? 1);
        
        switch($step) {
            case 1: // School Verification (auto-filled from URL)
                $visit_date = (string)($_POST['visit_date'] ?? '');
                
                if ($visit_date && isset($_SESSION['visit_data']['school_id'])) {
                    $_SESSION['visit_data']['visit_date'] = $visit_date;
                    header("Location: visit_add.php?step=2");
                    exit;
                } else {
                    $error = "Please select visit date";
                }
                break;
                
            case 2: // Visit Response
                $authority_person = (string)($_POST['authority_person'] ?? '');
                $letter_received = isset($_POST['letter_received']) ? 1 : 0;
                $permission_status = (string)($_POST['permission_status'] ?? '');
                $interest_status = (string)($_POST['interest_status'] ?? '');
                $phone = trim((string)($_POST['phone'] ?? ''));
                $optional_phone = trim((string)($_POST['optional_phone'] ?? ''));
                $whatsapp = trim((string)($_POST['whatsapp'] ?? ''));
                $not_allowed_reason = trim((string)($_POST['not_allowed_reason'] ?? ''));
                $skip_to_step4 = (int)($_POST['skip_to_step4'] ?? 0);
                
                $errors = [];
                
                if ($permission_status === 'NOT_ALLOWED') {
                    if (empty($not_allowed_reason)) {
                        $errors[] = "Please provide reason for not allowing permission";
                    }
                    // Save just the permission status and reason
                    $_SESSION['visit_data'] = array_merge($_SESSION['visit_data'], [
                        'authority_person' => $authority_person,
                        'letter_received' => $letter_received,
                        'permission_status' => $permission_status,
                        'not_allowed_reason' => $not_allowed_reason,
                        'interest_status' => 'NOT_APPLICABLE',
                        'phone' => '',
                        'optional_phone' => '',
                        'whatsapp' => ''
                    ]);
                    
                    if (empty($errors)) {
                        header("Location: visit_add.php?step=4");
                        exit;
                    }
                } else {
                    // Regular validation for GRANTED/PENDING
                    if (empty($authority_person)) $errors[] = "Please select who you met with";
                    if (empty($permission_status)) $errors[] = "Permission status is required";
                    if (empty($interest_status)) $errors[] = "Interest status is required";
                    if (empty($phone)) $errors[] = "Phone number is required";
                    if (!empty($phone) && !preg_match('/^[0-9]{10,15}$/', preg_replace('/[^0-9]/', '', $phone))) {
                        $errors[] = "Invalid phone number format (10-15 digits)";
                    }
                    
                    if (empty($errors)) {
                        $_SESSION['visit_data'] = array_merge($_SESSION['visit_data'], [
                            'authority_person' => $authority_person,
                            'letter_received' => $letter_received,
                            'permission_status' => $permission_status,
                            'interest_status' => $interest_status,
                            'phone' => $phone,
                            'optional_phone' => $optional_phone,
                            'whatsapp' => $whatsapp,
                            'not_allowed_reason' => ''
                        ]);
                        
                        // If skip_to_step4 is set, go directly to step 4, otherwise step 3
                        if ($skip_to_step4) {
                            header("Location: visit_add.php?step=4");
                        } else {
                            header("Location: visit_add.php?step=3");
                        }
                        exit;
                    }
                }
                
                if (!empty($errors)) {
                    $error = implode("<br>", $errors);
                }
                break;
                
            case 3: // Student Interaction
                $classes = $_POST['class'] ?? [];
                $interested_counts = $_POST['interested_count'] ?? [];
                $student_interactions = [];
                
                foreach ($classes as $key => $class) {
                    if ($class && isset($interested_counts[$key]) && $interested_counts[$key] > 0) {
                        $student_interactions[] = [
                            'class' => $class,
                            'interested_count' => (int)$interested_counts[$key]
                        ];
                    }
                }
                
                if (!empty($student_interactions)) {
                    $_SESSION['visit_data']['student_interactions'] = $student_interactions;
                    header("Location: visit_add.php?step=4");
                    exit;
                } else {
                    $error = "Please add at least one class interaction";
                }
                break;
                
            case 4: // GPS & Photos
                $latitude = (float)($_POST['latitude'] ?? 0);
                $longitude = (float)($_POST['longitude'] ?? 0);
                $accuracy_m = (float)($_POST['accuracy'] ?? 0);
                $gps_captured_at = (string)($_POST['gps_captured_at'] ?? '');
                $self_declaration = isset($_POST['self_declaration']) ? 1 : 0;
                
                $photo1_base64 = (string)($_POST['photo1_base64'] ?? '');
                
                if ($latitude == 0 || $longitude == 0) {
                    $error = "GPS location is required (accuracy < 150m)";
                } elseif ($accuracy_m > 150) {
                    $error = "GPS accuracy must be less than 150 meters. Current: " . round($accuracy_m) . "m";
                } elseif (empty($photo1_base64) && empty($_FILES['photo1']['name'])) {
                    $error = "Selfie with school name board is required";
                } elseif (!$self_declaration) {
                    $error = "Please accept the self declaration";
                } else {
                    try {
                        $pdo->beginTransaction();
                        
                        // Get school name
                        $school_name = $_SESSION['visit_data']['school_details']['name'] ?? 'Unknown School';
                        
                        // Process photo
                        $photo1_path = null;
                        if (!empty($photo1_base64)) {
                            $photo1_path = process_base64_image(
                                $photo1_base64, 
                                $school_name, 
                                $rep_name, 
                                $_SESSION['visit_data']['visit_date'], 
                                $latitude, 
                                $longitude
                            );
                        } else {
                            $photo1_path = process_uploaded_photo(
                                $_FILES['photo1'], 
                                $school_name, 
                                $rep_name, 
                                $_SESSION['visit_data']['visit_date'], 
                                $latitude, 
                                $longitude
                            );
                        }
                        
                        // Save main visit data
                        $st = $pdo->prepare("
                            INSERT INTO school_visits
                            (school_id, representative_id, representative_name, permission_status, interest_status, 
                             authority_person, not_allowed_reason, phone, optional_phone, whatsapp, letter_received, 
                             latitude, longitude, accuracy_m, gps_captured_at, photo1_path, 
                             self_declaration, visited_at)
                            VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
                        ");
                        
                        $st->execute([
                            $_SESSION['visit_data']['school_id'],
                            $uid,
                            $rep_name,
                            $_SESSION['visit_data']['permission_status'],
                            $_SESSION['visit_data']['interest_status'],
                            $_SESSION['visit_data']['authority_person'],
                            $_SESSION['visit_data']['not_allowed_reason'] ?: null,
                            $_SESSION['visit_data']['phone'] ? preg_replace('/[^0-9]/', '', $_SESSION['visit_data']['phone']) : null,
                            $_SESSION['visit_data']['optional_phone'] ? preg_replace('/[^0-9]/', '', $_SESSION['visit_data']['optional_phone']) : null,
                            $_SESSION['visit_data']['whatsapp'] ? preg_replace('/[^0-9]/', '', $_SESSION['visit_data']['whatsapp']) : null,
                            $_SESSION['visit_data']['letter_received'],
                            $latitude,
                            $longitude,
                            $accuracy_m,
                            $gps_captured_at,
                            $photo1_path,
                            $self_declaration,
                            $_SESSION['visit_data']['visit_date']
                        ]);
                        
                        $visit_id = $pdo->lastInsertId();
                        
                        // Save student interactions (only if permission was granted/pending)
                        if (!empty($_SESSION['visit_data']['student_interactions'])) {
                            $st = $pdo->prepare("
                                INSERT INTO visit_student_interactions 
                                (visit_id, class, interested_count) 
                                VALUES (?,?,?)
                            ");
                            foreach ($_SESSION['visit_data']['student_interactions'] as $interaction) {
                                $st->execute([$visit_id, $interaction['class'], $interaction['interested_count']]);
                            }
                        }
                        

                        // Insert pending verification if not already present
                        $st = $pdo->prepare("SELECT id FROM school_verification WHERE school_id = ? AND representative_id = ? AND status = 'PENDING'");
                        $st->execute([
                            $_SESSION['visit_data']['school_id'],
                            $uid
                        ]);
                        if (!$st->fetchColumn()) {
                            $st = $pdo->prepare("INSERT INTO school_verification (school_id, representative_id, status, requested_at) VALUES (?, ?, 'PENDING', NOW())");
                            $st->execute([
                                $_SESSION['visit_data']['school_id'],
                                $uid
                            ]);
                        }

                        $pdo->commit();

                        // Clear session data
                        unset($_SESSION['visit_data']);

                        $success = "Visit saved successfully!";
                        $current_step = 5; // Success step
                        
                    } catch (Exception $e) {
                        $pdo->rollBack();
                        $error = "Error saving visit: " . $e->getMessage();
                    }
                }
                break;
        }
    }
}

function upload_error_message($code) {
    switch ($code) {
        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
            return "File too large";
        case UPLOAD_ERR_PARTIAL:
            return "Partial upload";
        case UPLOAD_ERR_NO_FILE:
            return "No file";
        default:
            return "Unknown error";
    }
}

function process_base64_image($base64_string, $school_name, $rep_name, $visit_date, $lat, $long) {
    if (preg_match('/^data:image\/(\w+);base64,/', $base64_string, $matches)) {
        $image_type = $matches[1];
        $base64_string = substr($base64_string, strpos($base64_string, ',') + 1);
    } else {
        throw new Exception("Invalid base64 image format");
    }
    
    $image_data = base64_decode($base64_string);
    if ($image_data === false) {
        throw new Exception("Base64 decode failed");
    }
    
    if (!in_array($image_type, ['jpeg', 'jpg', 'png'])) {
        throw new Exception("Only JPG/PNG images are allowed");
    }
    
    $ext = $image_type === 'jpeg' ? 'jpg' : $image_type;
    $filename = uniqid('selfie_' . date('Ymd_His') . '_', true) . '.' . $ext;
    $upload_path = __DIR__ . '/../public/uploads/visits/' . $filename;
    $web_path = '/school-crm/public/uploads/visits/' . $filename;
    
    file_put_contents($upload_path, $image_data);
    
    apply_watermark($upload_path, $school_name, $rep_name, $visit_date, $lat, $long);
    
    return $web_path;
}

function process_uploaded_photo($file, $school_name, $rep_name, $visit_date, $lat, $long) {
    if ($file['error'] !== UPLOAD_ERR_OK) {
        throw new Exception("Upload error: " . upload_error_message($file['error']));
    }
    
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);
    
    if (!in_array($mime, ['image/jpeg', 'image/png'])) {
        throw new Exception("Only JPG/PNG images are allowed");
    }
    
    if ($file['size'] > 2 * 1024 * 1024) {
        throw new Exception("File size must be less than 2MB");
    }
    
    $ext = $mime === 'image/jpeg' ? 'jpg' : 'png';
    $filename = uniqid('selfie_' . date('Ymd_His') . '_', true) . '.' . $ext;
    $upload_path = __DIR__ . '/../public/uploads/visits/' . $filename;
    $web_path = '/school-crm/public/uploads/visits/' . $filename;
    
    if (!move_uploaded_file($file['tmp_name'], $upload_path)) {
        throw new Exception("Failed to save uploaded file");
    }
    
    apply_watermark($upload_path, $school_name, $rep_name, $visit_date, $lat, $long);
    
    return $web_path;
}

function apply_watermark($image_path, $school_name, $rep_name, $visit_date, $lat, $long) {
    try {
        $info = getimagesize($image_path);
        if (!$info) return false;
        
        $mime = $info['mime'];
        
        switch ($mime) {
            case 'image/jpeg':
                $im = imagecreatefromjpeg($image_path);
                break;
            case 'image/png':
                $im = imagecreatefrompng($image_path);
                imagealphablending($im, false);
                imagesavealpha($im, true);
                break;
            default:
                return false;
        }
        
        if (!$im) return false;
        
        $program_text = "Grand Dance Talent Hunt 2026";
        $school_text = "School: " . $school_name;
        $rep_text = "Rep: " . $rep_name;
        $date_text = "Date: " . date('d-m-Y H:i', strtotime($visit_date));
        $gps_text = "GPS: " . round($lat, 6) . "," . round($long, 6);
        
        $white = imagecolorallocatealpha($im, 255, 255, 255, 0);
        $black = imagecolorallocatealpha($im, 0, 0, 0, 50);
        $bg_color = imagecolorallocatealpha($im, 0, 0, 0, 70);
        
        $width = imagesx($im);
        $height = imagesy($im);
        
        $font_size = max(12, min(24, round($width / 40)));
        
        $font_path = __DIR__ . '/../assets/fonts/arial.ttf';
        $use_ttf = file_exists($font_path) && function_exists('imagettftext');
        
        $padding = 15;
        $line_height = $use_ttf ? $font_size + 8 : 20;
        $y = $height - $padding - (5 * $line_height) - 10;
        
        $bg_height = 5 * $line_height + 10;
        
        if ($use_ttf) {
            $max_width = 0;
            $texts = [$program_text, $school_text, $rep_text, $date_text, $gps_text];
            foreach ($texts as $text) {
                $bbox = imagettfbbox($font_size, 0, $font_path, $text);
                $text_width = $bbox[2] - $bbox[0];
                $max_width = max($max_width, $text_width);
            }
            $bg_width = $max_width + 30;
            
            imagefilledrectangle($im, $padding - 5, $y - 5, $padding + $bg_width, $y + $bg_height, $bg_color);
            
            foreach ($texts as $i => $text) {
                imagettftext($im, $font_size, 0, $padding + 2, $y + 2 + ($i * $line_height), $black, $font_path, $text);
                imagettftext($im, $font_size, 0, $padding, $y + ($i * $line_height), $white, $font_path, $text);
            }
        } else {
            $font = 5;
            $char_height = imagefontheight($font);
            $line_height = $char_height + 4;
            
            imagefilledrectangle($im, $padding - 5, $y - 5, $width - $padding, $y + $bg_height, $bg_color);
            
            $texts = [$program_text, $school_text, $rep_text, $date_text, $gps_text];
            foreach ($texts as $i => $text) {
                imagestring($im, $font, $padding + 2, $y + 2 + ($i * $line_height), $text, $black);
                imagestring($im, $font, $padding, $y + ($i * $line_height), $text, $white);
            }
        }
        
        switch ($mime) {
            case 'image/jpeg':
                imagejpeg($im, $image_path, 90);
                break;
            case 'image/png':
                imagepng($im, $image_path, 9);
                break;
        }
        
        imagedestroy($im);
        return true;
        
    } catch (Exception $e) {
        error_log("Watermark failed: " . $e->getMessage());
        return false;
    }
}

$page_title = "Add Visit";
require_once __DIR__ . "/partials/header.php";
?>

<!-- App-style CSS -->
<style>
:root {
    --primary: #4361ee;
    --success: #06d6a0;
    --warning: #ffb703;
    --danger: #ef476f;
    --dark: #073b4c;
    --light: #f8f9fa;
    --gray: #6c757d;
    --border: #e9ecef;
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    background: #f5f7fa;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
}

/* App Container */
.app-container {
    max-width: 1200px;
    margin: 0 auto;
    background: white;
    min-height: 100vh;
    box-shadow: 0 0 20px rgba(0,0,0,0.05);
}

/* App Header */
.app-header {
    background: linear-gradient(135deg, var(--primary), #3a0ca3);
    color: white;
    padding: 20px;
    position: sticky;
    top: 0;
    z-index: 100;
}

.app-header h1 {
    font-size: 1.5rem;
    font-weight: 600;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 10px;
}

.app-header h1 i {
    font-size: 1.8rem;
}

.app-header .subtitle {
    font-size: 0.85rem;
    opacity: 0.9;
    margin-top: 5px;
}

/* Step Progress */
.step-progress {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    background: white;
    border-bottom: 1px solid var(--border);
}

.step-item {
    flex: 1;
    text-align: center;
    position: relative;
}

.step-item:not(:last-child)::after {
    content: '';
    position: absolute;
    top: 20px;
    right: -50%;
    width: 100%;
    height: 2px;
    background: var(--border);
    z-index: 1;
}

.step-item.active .step-number {
    background: var(--primary);
    color: white;
    border-color: var(--primary);
}

.step-item.completed .step-number {
    background: var(--success);
    color: white;
    border-color: var(--success);
}

.step-item.completed:not(:last-child)::after {
    background: var(--success);
}

.step-number {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: white;
    border: 2px solid var(--border);
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 10px;
    font-weight: 600;
    position: relative;
    z-index: 2;
    transition: all 0.3s;
}

.step-label {
    font-size: 0.8rem;
    color: var(--gray);
    font-weight: 500;
}

.step-item.active .step-label {
    color: var(--primary);
    font-weight: 600;
}

/* Form Container */
.form-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
}

/* School Info Card */
.school-card {
    background: linear-gradient(135deg, #06d6a0 0%, #0ca678 100%);
    border-radius: 20px;
    padding: 25px;
    color: white;
    margin-bottom: 25px;
    box-shadow: 0 10px 30px rgba(6, 214, 160, 0.3);
    animation: slideDown 0.5s ease;
}

.school-card h3 {
    font-size: 1.3rem;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.school-card h3 i {
    font-size: 1.8rem;
}

.school-info-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
}

.school-info-item {
    background: rgba(255,255,255,0.1);
    padding: 15px;
    border-radius: 12px;
    backdrop-filter: blur(10px);
}

.school-info-label {
    font-size: 0.75rem;
    opacity: 0.8;
    margin-bottom: 5px;
}

.school-info-value {
    font-size: 1rem;
    font-weight: 600;
}

/* Form Section */
.form-section {
    background: white;
    border-radius: 20px;
    padding: 25px;
    margin-bottom: 25px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.03);
    border: 1px solid var(--border);
}

.section-title {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 25px;
    font-size: 1.2rem;
    font-weight: 600;
    color: var(--dark);
}

.section-title i {
    color: var(--primary);
    font-size: 1.5rem;
}

/* Form Elements */
.form-group {
    margin-bottom: 20px;
}

.form-label {
    display: block;
    font-size: 0.9rem;
    font-weight: 500;
    color: var(--dark);
    margin-bottom: 8px;
}

.form-label i {
    color: var(--primary);
    margin-right: 6px;
}

.form-control, .form-select {
    width: 100%;
    padding: 15px;
    border: 2px solid var(--border);
    border-radius: 15px;
    font-size: 1rem;
    transition: all 0.3s;
}

.form-control:focus, .form-select:focus {
    border-color: var(--primary);
    outline: none;
    box-shadow: 0 0 0 4px rgba(67, 97, 238, 0.1);
}

/* Checkbox Group */
.checkbox-group {
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
}

.checkbox-item {
    display: flex;
    align-items: center;
    gap: 8px;
    background: var(--light);
    padding: 15px 25px;
    border-radius: 30px;
    cursor: pointer;
    transition: all 0.3s;
    flex: 1;
}

.checkbox-item:active {
    transform: scale(0.98);
}

.checkbox-item input[type="checkbox"] {
    width: 22px;
    height: 22px;
    accent-color: var(--success);
}

/* Radio Group */
.radio-group {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
}

.radio-item {
    flex: 1;
    min-width: 120px;
}

.radio-item input[type="radio"] {
    display: none;
}

.radio-item label {
    display: block;
    text-align: center;
    padding: 15px;
    border: 2px solid var(--border);
    border-radius: 15px;
    cursor: pointer;
    transition: all 0.3s;
    font-weight: 500;
}

.radio-item input[type="radio"]:checked + label {
    background: var(--primary);
    color: white;
    border-color: var(--primary);
}

/* Class Interaction Row */
.class-row {
    display: grid;
    grid-template-columns: 1fr 1fr auto;
    gap: 15px;
    margin-bottom: 15px;
    align-items: center;
    background: var(--light);
    padding: 15px;
    border-radius: 15px;
}

.remove-class {
    background: var(--danger);
    color: white;
    border: none;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;
}

.remove-class:hover {
    transform: scale(1.1);
}

.add-class {
    background: var(--success);
    color: white;
    border: none;
    padding: 15px 25px;
    border-radius: 30px;
    display: inline-flex;
    align-items: center;
    gap: 10px;
    cursor: pointer;
    font-weight: 500;
    margin-top: 10px;
}

/* GPS Section */
.gps-section {
    background: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);
    border-radius: 20px;
    padding: 25px;
    margin-bottom: 25px;
}

.gps-button {
    background: linear-gradient(135deg, var(--success), #0ca678);
    color: white;
    border: none;
    padding: 18px;
    border-radius: 30px;
    font-size: 1.1rem;
    font-weight: 600;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    margin-bottom: 15px;
    cursor: pointer;
    transition: all 0.3s;
}

.gps-button:active {
    transform: scale(0.98);
}

.accuracy-warning {
    text-align: center;
    padding: 10px;
    border-radius: 10px;
    margin: 10px 0;
    font-weight: 500;
}

.accuracy-warning.good {
    background: #d4edda;
    color: #155724;
}

.accuracy-warning.bad {
    background: #f8d7da;
    color: #721c24;
}

/* Camera Section */
.camera-section {
    background: var(--light);
    border-radius: 20px;
    padding: 25px;
    margin-bottom: 25px;
}

.camera-preview {
    width: 100%;
    max-height: 400px;
    object-fit: contain;
    background: #000;
    border-radius: 15px;
    margin: 15px 0;
}

.camera-actions {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 15px;
    margin: 15px 0;
}

.camera-btn {
    padding: 15px;
    border: none;
    border-radius: 15px;
    font-weight: 500;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    cursor: pointer;
    transition: all 0.3s;
}

.camera-btn.primary {
    background: var(--primary);
    color: white;
}

.camera-btn.success {
    background: var(--success);
    color: white;
}

.camera-btn.danger {
    background: var(--danger);
    color: white;
}

/* Self Declaration */
.declaration-card {
    background: linear-gradient(135deg, #fff3cd 0%, #ffe69c 100%);
    border-radius: 20px;
    padding: 25px;
    margin: 25px 0;
    border-left: 5px solid #ffc107;
}

.declaration-check {
    display: flex;
    align-items: center;
    gap: 15px;
    margin-top: 15px;
}

.declaration-check input {
    width: 25px;
    height: 25px;
}

/* Navigation Buttons */
.nav-buttons {
    display: flex;
    justify-content: space-between;
    gap: 15px;
    margin-top: 25px;
}

.btn {
    padding: 15px 30px;
    border: none;
    border-radius: 15px;
    font-size: 1rem;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 10px;
    cursor: pointer;
    transition: all 0.3s;
    text-decoration: none;
}

.btn-primary {
    background: var(--primary);
    color: white;
    flex: 1;
    justify-content: center;
}

.btn-secondary {
    background: var(--light);
    color: var(--dark);
    border: 2px solid var(--border);
}

.btn-success {
    background: var(--success);
    color: white;
    flex: 1;
    justify-content: center;
}

/* Success Screen */
.success-screen {
    text-align: center;
    padding: 50px 20px;
}

.success-icon {
    width: 100px;
    height: 100px;
    background: var(--success);
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 3rem;
    margin: 0 auto 25px;
    animation: scaleIn 0.5s;
}

@keyframes scaleIn {
    from {
        transform: scale(0);
    }
    to {
        transform: scale(1);
    }
}

@keyframes slideDown {
    from {
        opacity: 0;
        transform: translateY(-20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

/* Alerts */
.alert {
    padding: 15px 20px;
    border-radius: 15px;
    margin: 15px 0;
    display: flex;
    align-items: center;
    gap: 10px;
    animation: slideDown 0.3s;
}

.alert-success {
    background: #d4edda;
    color: #155724;
    border-left: 4px solid #28a745;
}

.alert-danger {
    background: #f8d7da;
    color: #721c24;
    border-left: 4px solid #dc3545;
}

/* Loading Spinner */
.loading-spinner {
    width: 20px;
    height: 20px;
    border: 3px solid rgba(255,255,255,.3);
    border-radius: 50%;
    border-top-color: white;
    animation: spin 1s ease-in-out infinite;
    display: inline-block;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}

/* Mobile Responsive */
@media (max-width: 768px) {
    .app-container {
        max-width: 100%;
    }
    
    .step-label {
        font-size: 0.7rem;
    }
    
    .class-row {
        grid-template-columns: 1fr;
    }
    
    .camera-actions {
        grid-template-columns: 1fr;
    }
    
    .radio-group {
        flex-direction: column;
    }
    
    .checkbox-group {
        flex-direction: column;
    }
    
    .school-info-grid {
        grid-template-columns: 1fr;
    }
}
</style>

<!-- Bootstrap Icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">

<div class="app-container">
    <!-- App Header -->
    <div class="app-header">
        <h1>
            <i class="bi bi-building"></i>
            School Visit Report
        </h1>
        <div class="subtitle">
            <i class="bi bi-person"></i> <?= htmlspecialchars($rep_name) ?>
        </div>
    </div>

    <!-- Step Progress -->
    <div class="step-progress">
        <div class="step-item <?= $current_step >= 1 ? 'completed' : '' ?> <?= $current_step == 1 ? 'active' : '' ?>">
            <div class="step-number">1</div>
            <div class="step-label">School Info</div>
        </div>
        <div class="step-item <?= $current_step >= 2 ? 'completed' : '' ?> <?= $current_step == 2 ? 'active' : '' ?>">
            <div class="step-number">2</div>
            <div class="step-label">Visit Response</div>
        </div>
        <div class="step-item <?= $current_step >= 3 ? 'completed' : '' ?> <?= $current_step == 3 ? 'active' : '' ?>">
            <div class="step-number">3</div>
            <div class="step-label">Student Interaction</div>
        </div>
        <div class="step-item <?= $current_step >= 4 ? 'completed' : '' ?> <?= $current_step == 4 ? 'active' : '' ?>">
            <div class="step-number">4</div>
            <div class="step-label">GPS & Selfie</div>
        </div>
    </div>

    <!-- Alerts -->
    <?php if ($success): ?>
        <div class="alert alert-success" style="margin: 15px;">
            <i class="bi bi-check-circle-fill"></i>
            <?= htmlspecialchars($success) ?>
        </div>
    <?php endif; ?>
    
    <?php if ($error): ?>
        <div class="alert alert-danger" style="margin: 15px;">
            <i class="bi bi-exclamation-triangle-fill"></i>
            <?= $error ?>
        </div>
    <?php endif; ?>

    <!-- Step 1: School Information (Auto-filled from URL) -->
    <?php if ($current_step == 1): ?>
    <div class="form-container">
        <?php if ($school_details): ?>
        <!-- School Info Card -->
        <div class="school-card">
            <h3>
                <i class="bi bi-building"></i>
                <?= htmlspecialchars($school_details['name']) ?>
            </h3>
            <div class="school-info-grid">
                <div class="school-info-item">
                    <div class="school-info-label">District</div>
                    <div class="school-info-value"><?= htmlspecialchars($school_details['district_name'] ?? '') ?></div>
                </div>
                <div class="school-info-item">
                    <div class="school-info-label">Block</div>
                    <div class="school-info-value"><?= htmlspecialchars($school_details['block_name'] ?? '') ?></div>
                </div>
                <div class="school-info-item">
                    <div class="school-info-label">GP</div>
                    <div class="school-info-value"><?= htmlspecialchars($school_details['gp_name'] ?? '') ?></div>
                </div>
                <div class="school-info-item">
                    <div class="school-info-label">Category</div>
                    <div class="school-info-value"><?= htmlspecialchars($school_details['category'] ?? '') ?></div>
                </div>
                <div class="school-info-item">
                    <div class="school-info-label">Address</div>
                    <div class="school-info-value"><?= htmlspecialchars($school_details['address'] ?? '') ?></div>
                </div>
            </div>
        </div>

        <form method="post">
            <input type="hidden" name="csrf" value="<?= htmlspecialchars(csrf_token()) ?>">
            <input type="hidden" name="step" value="1">

            <div class="form-section">
                <div class="section-title">
                    <i class="bi bi-calendar-check"></i>
                    Visit Date
                </div>
                <div class="form-group">
                    <input type="date" class="form-control" name="visit_date" 
                           value="<?= htmlspecialchars(date('Y-m-d')) ?>" required>
                </div>
            </div>

            <div class="nav-buttons">
                <a href="/school-crm/public/my_schools.php" class="btn btn-secondary">
                    <i class="bi bi-arrow-left"></i> Back to Schools
                </a>
                <button type="submit" class="btn btn-primary">
                    Continue <i class="bi bi-arrow-right"></i>
                </button>
            </div>
        </form>
        <?php else: ?>
        <div class="alert alert-danger">
            <i class="bi bi-exclamation-triangle-fill"></i>
            No school selected. Please select a school from the <a href="/school-crm/public/my_schools.php">My Schools</a> page.
        </div>
        <?php endif; ?>
    </div>

    <!-- Step 2: Visit Response -->
    <?php elseif ($current_step == 2 && isset($_SESSION['visit_data']['school_details'])): ?>
    <div class="form-container">
        <!-- School Info Card (Always Visible) -->
        <div class="school-card">
            <h3>
                <i class="bi bi-building"></i>
                <?= htmlspecialchars($_SESSION['visit_data']['school_details']['name']) ?>
            </h3>
            <div class="school-info-grid">
                <div class="school-info-item">
                    <div class="school-info-label">District</div>
                    <div class="school-info-value"><?= htmlspecialchars($_SESSION['visit_data']['school_details']['district_name'] ?? '') ?></div>
                </div>
                <div class="school-info-item">
                    <div class="school-info-label">Block</div>
                    <div class="school-info-value"><?= htmlspecialchars($_SESSION['visit_data']['school_details']['block_name'] ?? '') ?></div>
                </div>
                <div class="school-info-item">
                    <div class="school-info-label">GP</div>
                    <div class="school-info-value"><?= htmlspecialchars($_SESSION['visit_data']['school_details']['gp_name'] ?? '') ?></div>
                </div>
                <div class="school-info-item">
                    <div class="school-info-label">Visit Date</div>
                    <div class="school-info-value"><?= date('d M Y', strtotime($_SESSION['visit_data']['visit_date'])) ?></div>
                </div>
            </div>
        </div>

        <form method="post" id="visitResponseForm">
            <input type="hidden" name="csrf" value="<?= htmlspecialchars(csrf_token()) ?>">
            <input type="hidden" name="step" value="2">
            <input type="hidden" name="skip_to_step4" id="skip_to_step4" value="0">

            <div class="form-section">
                <div class="section-title">
                    <i class="bi bi-person-badge"></i>
                    Authority Information
                </div>

                <div class="form-group">
                    <label class="form-label">Met With <span class="text-danger">*</span></label>
                    <select class="form-select" name="authority_person" id="authority_person" required>
                        <option value="">Select Person</option>
                        <option value="HEAD_SIR">Head Sir</option>
                        <option value="HEAD_MAAM">Head Ma'am</option>
                        <option value="TEACHER">Teacher</option>
                        <option value="STAFF">Staff</option>
                        <option value="OTHER">Other</option>
                    </select>
                </div>

                <div class="checkbox-group">
                    <label class="checkbox-item">
                        <input type="checkbox" name="letter_received" value="1" id="letter_received">
                        <span>📄 Letter Received</span>
                    </label>
                </div>
            </div>

            <div class="form-section">
                <div class="section-title">
                    <i class="bi bi-chat-dots"></i>
                    Response Status
                </div>

                <div class="form-group">
                    <label class="form-label">Permission Status <span class="text-danger">*</span></label>
                    <div class="radio-group" id="permission_radio_group">
                        <div class="radio-item">
                            <input type="radio" name="permission_status" id="perm_granted" value="GRANTED" required>
                            <label for="perm_granted">✅ Granted</label>
                        </div>
                        <div class="radio-item">
                            <input type="radio" name="permission_status" id="perm_pending" value="PENDING">
                            <label for="perm_pending">⏳ Pending</label>
                        </div>
                        <div class="radio-item">
                            <input type="radio" name="permission_status" id="perm_not_allowed" value="NOT_ALLOWED">
                            <label for="perm_not_allowed">❌ Not Allowed</label>
                        </div>
                    </div>
                </div>

                <!-- Reason for Not Allowed (hidden by default) -->
                <div id="not_allowed_reason_container" style="display: none; margin-top: 20px; padding: 20px; background: #fff3cd; border-radius: 15px; border-left: 4px solid #ffc107;">
                    <label class="form-label" style="color: #856404;">
                        <i class="bi bi-exclamation-triangle-fill"></i> Reason for Not Allowed <span class="text-danger">*</span>
                    </label>
                    <textarea class="form-control" name="not_allowed_reason" id="not_allowed_reason" rows="3" placeholder="Please specify why permission was not allowed..."></textarea>
                    <small class="text-muted" style="color: #856404 !important; margin-top: 5px; display: block;">This field is required when permission is not allowed</small>
                </div>

                <div class="form-group" id="interest_status_container">
                    <label class="form-label">Interest Status <span class="text-danger">*</span></label>
                    <div class="radio-group">
                        <div class="radio-item">
                            <input type="radio" name="interest_status" id="int_very" value="VERY_INTERESTED">
                            <label for="int_very">🔥 Very Interested</label>
                        </div>
                        <div class="radio-item">
                            <input type="radio" name="interest_status" id="int_yes" value="YES">
                            <label for="int_yes">👍 Interested</label>
                        </div>
                        <div class="radio-item">
                            <input type="radio" name="interest_status" id="int_maybe" value="MAYBE">
                            <label for="int_maybe">🤔 Maybe</label>
                        </div>
                        <div class="radio-item">
                            <input type="radio" name="interest_status" id="int_no" value="NO">
                            <label for="int_no">👎 Not Interested</label>
                        </div>
                        <div class="radio-item">
                            <input type="radio" name="interest_status" id="int_later" value="CONTACT_LATER">
                            <label for="int_later">📅 Contact Later</label>
                        </div>
                    </div>
                </div>
            </div>

            <div class="form-section" id="contact_info_section">
                <div class="section-title">
                    <i class="bi bi-telephone"></i>
                    Contact Numbers
                </div>

                <div class="form-group">
                    <label class="form-label">Phone <span class="text-danger">*</span></label>
                    <input type="tel" class="form-control" name="phone" id="phone" 
                           placeholder="10-15 digits">
                </div>

                <div class="form-group">
                    <label class="form-label">Optional Phone</label>
                    <input type="tel" class="form-control" name="optional_phone" id="optional_phone" 
                           placeholder="Alternate number">
                </div>

                <div class="form-group">
                    <label class="form-label">WhatsApp</label>
                    <input type="tel" class="form-control" name="whatsapp" id="whatsapp" 
                           placeholder="WhatsApp number">
                </div>
            </div>

            <div class="nav-buttons">
                <a href="visit_add.php?step=1" class="btn btn-secondary">
                    <i class="bi bi-arrow-left"></i> Back
                </a>
                <button type="submit" class="btn btn-primary" id="continueBtn">
                    Continue <i class="bi bi-arrow-right"></i>
                </button>
            </div>
        </form>
    </div>

    <!-- Step 3: Student Interaction -->
    <?php elseif ($current_step == 3): ?>
    <div class="form-container">
        <!-- School Info Card -->
        <div class="school-card">
            <h3>
                <i class="bi bi-building"></i>
                <?= htmlspecialchars($_SESSION['visit_data']['school_details']['name']) ?>
            </h3>
            <div class="school-info-grid">
                <div class="school-info-item">
                    <div class="school-info-label">Met With</div>
                    <div class="school-info-value"><?= $_SESSION['visit_data']['authority_person'] ?></div>
                </div>
                <div class="school-info-item">
                    <div class="school-info-label">Permission</div>
                    <div class="school-info-value"><?= $_SESSION['visit_data']['permission_status'] ?></div>
                </div>
                <div class="school-info-item">
                    <div class="school-info-label">Interest</div>
                    <div class="school-info-value"><?= $_SESSION['visit_data']['interest_status'] ?></div>
                </div>
            </div>
        </div>

        <form method="post">
            <input type="hidden" name="csrf" value="<?= htmlspecialchars(csrf_token()) ?>">
            <input type="hidden" name="step" value="3">

            <div class="form-section">
                <div class="section-title">
                    <i class="bi bi-people"></i>
                    Class-wise Student Interaction
                </div>

                <div id="class-container">
                    <!-- Class rows will be added here -->
                    <div class="class-row">
                        <select class="form-select" name="class[]" required>
                            <option value="">Select Class</option>
                            <?php for($i = 1; $i <= 12; $i++): ?>
                            <option value="<?= $i ?>">Class <?= $i ?></option>
                            <?php endfor; ?>
                        </select>
                        <input type="number" class="form-control" name="interested_count[]" 
                               placeholder="Interested Students" min="1" required>
                        <button type="button" class="remove-class" onclick="this.closest('.class-row').remove()">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                </div>

                <button type="button" class="add-class" onclick="addClassRow()">
                    <i class="bi bi-plus-circle"></i> Add Another Class
                </button>
            </div>

            <div class="nav-buttons">
                <a href="visit_add.php?step=2" class="btn btn-secondary">
                    <i class="bi bi-arrow-left"></i> Back
                </a>
                <button type="submit" class="btn btn-primary">
                    Continue <i class="bi bi-arrow-right"></i>
                </button>
            </div>
        </form>
    </div>

    <!-- Step 4: GPS & Selfie -->
    <?php elseif ($current_step == 4): ?>
    <div class="form-container">
        <!-- School Info Card -->
        <div class="school-card">
            <h3>
                <i class="bi bi-building"></i>
                <?= htmlspecialchars($_SESSION['visit_data']['school_details']['name']) ?>
            </h3>
            <div class="school-info-grid">
                <?php if ($_SESSION['visit_data']['permission_status'] !== 'NOT_ALLOWED'): ?>
                <div class="school-info-item">
                    <div class="school-info-label">Classes</div>
                    <div class="school-info-value"><?= count($_SESSION['visit_data']['student_interactions'] ?? []) ?> classes</div>
                </div>
                <div class="school-info-item">
                    <div class="school-info-label">Total Interested</div>
                    <div class="school-info-value">
                        <?= array_sum(array_column($_SESSION['visit_data']['student_interactions'] ?? [], 'interested_count')) ?>
                    </div>
                </div>
                <?php else: ?>
                <div class="school-info-item">
                    <div class="school-info-label">Permission</div>
                    <div class="school-info-value">❌ Not Allowed</div>
                </div>
                <div class="school-info-item">
                    <div class="school-info-label">Reason</div>
                    <div class="school-info-value"><?= htmlspecialchars($_SESSION['visit_data']['not_allowed_reason'] ?? '') ?></div>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <form method="post" enctype="multipart/form-data" id="visitForm">
            <input type="hidden" name="csrf" value="<?= htmlspecialchars(csrf_token()) ?>">
            <input type="hidden" name="step" value="4">
            <input type="hidden" name="gps_captured_at" id="gps_captured_at" value="">
            <input type="hidden" name="photo1_base64" id="photo1_base64" value="">

            <!-- GPS Section -->
            <div class="gps-section">
                <div class="section-title">
                    <i class="bi bi-satellite"></i>
                    GPS Location (Required, Accuracy < 150m)
                </div>

                <button type="button" class="gps-button" id="captureGps">
                    <i class="bi bi-crosshair2"></i>
                    <span id="gpsBtnText">📍 Get Current Location</span>
                    <span class="loading-spinner" id="gpsLoading" style="display: none;"></span>
                </button>

                <div id="gpsStatus" class="gps-status"></div>
                <div id="accuracyWarning" class="accuracy-warning" style="display: none;"></div>

                <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px; margin-top: 15px;">
                    <input type="text" name="latitude" id="latitude" placeholder="Latitude" readonly>
                    <input type="text" name="longitude" id="longitude" placeholder="Longitude" readonly>
                    <input type="text" name="accuracy" id="accuracy" placeholder="Accuracy" readonly>
                </div>
            </div>

            <!-- Selfie Section -->
            <div class="camera-section">
                <div class="section-title">
                    <i class="bi bi-camera-selfie"></i>
                    Selfie with School Name Board <span class="text-danger">*</span>
                </div>

                <div class="camera-actions">
                    <button type="button" class="camera-btn primary" onclick="startCamera(1)">
                        <i class="bi bi-camera"></i> Open Camera
                    </button>
                    <button type="button" class="camera-btn" onclick="switchCamera(1)">
                        <i class="bi bi-arrow-repeat"></i> Switch
                    </button>
                </div>

                <input type="file" class="form-control" name="photo1" id="photo1" 
                       accept="image/jpeg,image/png" style="margin: 15px 0;">
                
                <div id="cameraPreview1" style="display: none;">
                    <video id="video1" class="camera-preview" autoplay playsinline></video>
                    <div class="camera-actions">
                        <button type="button" class="camera-btn success" onclick="capturePhoto(1)">
                            <i class="bi bi-camera-fill"></i> Capture
                        </button>
                        <button type="button" class="camera-btn danger" onclick="stopCamera(1)">
                            <i class="bi bi-stop-circle"></i> Stop
                        </button>
                    </div>
                </div>
                
                <div id="photoPreview1" style="text-align: center;">
                    <!-- Preview will be shown here -->
                </div>
            </div>

            <!-- Self Declaration -->
            <div class="declaration-card">
                <i class="bi bi-shield-check" style="font-size: 2rem; color: #856404;"></i>
                <h4 style="margin: 15px 0;">Self Declaration</h4>
                <p style="margin-bottom: 20px;">I hereby declare that all information provided above is true and correct to the best of my knowledge. I have personally visited the school and captured the selfie with the school name board.</p>
                
                <div class="declaration-check">
                    <input type="checkbox" name="self_declaration" id="self_declaration" value="1" required>
                    <label for="self_declaration" style="font-weight: 600;">I confirm that the above information is true</label>
                </div>
            </div>

            <div class="nav-buttons">
                <a href="visit_add.php?step=3" class="btn btn-secondary" id="backToStep3">
                    <i class="bi bi-arrow-left"></i> Back
                </a>
                <button type="submit" class="btn btn-success" id="submitBtn" disabled>
                    <i class="bi bi-check-circle"></i> Submit Visit
                </button>
            </div>
        </form>
    </div>

    <!-- Step 5: Success -->
    <?php elseif ($current_step == 5): ?>
    <div class="success-screen">
        <div class="success-icon">
            <i class="bi bi-check-lg"></i>
        </div>
        <h2 style="margin-bottom: 20px;">Waiting for Admin Verification</h2>
        <p style="color: var(--gray); margin-bottom: 30px;">Your visit report has been submitted and is pending admin verification.</p>
        
        <div style="display: flex; gap: 15px; justify-content: center;">
            <a href="/school-crm/public/my_schools.php" class="btn btn-primary">
                <i class="bi bi-building"></i> Back to Schools
            </a>
            <a href="/school-crm/public/dashboard.php" class="btn btn-secondary">
                <i class="bi bi-house"></i> Dashboard
            </a>
        </div>
    </div>
    <?php endif; ?>
</div>

<script>
// Camera variables
let currentStream1 = null;
let currentDeviceId1 = null;
let allDevices = [];

// Add class row
function addClassRow() {
    const container = document.getElementById('class-container');
    const newRow = document.createElement('div');
    newRow.className = 'class-row';
    newRow.innerHTML = `
        <select class="form-select" name="class[]" required>
            <option value="">Select Class</option>
            <?php for($i = 1; $i <= 12; $i++): ?>
            <option value="<?= $i ?>">Class <?= $i ?></option>
            <?php endfor; ?>
        </select>
        <input type="number" class="form-control" name="interested_count[]" 
               placeholder="Interested Students" min="1" required>
        <button type="button" class="remove-class" onclick="this.closest('.class-row').remove()">
            <i class="bi bi-trash"></i>
        </button>
    `;
    container.appendChild(newRow);
}

// Camera functions
async function getCameraDevices() {
    try {
        const devices = await navigator.mediaDevices.enumerateDevices();
        allDevices = devices.filter(device => device.kind === 'videoinput');
        return allDevices;
    } catch (err) {
        console.error('Error getting cameras:', err);
        return [];
    }
}

async function startCamera(photoNum) {
    try {
        const videoId = `video${photoNum}`;
        const previewId = `cameraPreview${photoNum}`;
        const video = document.getElementById(videoId);
        
        stopCamera(photoNum);
        
        const constraints = {
            video: {
                facingMode: 'user', // Front camera for selfie
                width: { ideal: 1920 },
                height: { ideal: 1080 }
            }
        };
        
        if (photoNum === 1 && currentDeviceId1) {
            constraints.video.deviceId = { exact: currentDeviceId1 };
        }
        
        const stream = await navigator.mediaDevices.getUserMedia(constraints);
        
        if (photoNum === 1) {
            currentStream1 = stream;
        }
        
        video.srcObject = stream;
        await video.play();
        
        document.getElementById(previewId).style.display = 'block';
        
    } catch (err) {
        console.error('Camera error:', err);
        alert('Please allow camera access for selfie');
    }
}

function stopCamera(photoNum) {
    const stream = photoNum === 1 ? currentStream1 : null;
    const previewId = `cameraPreview${photoNum}`;
    
    if (stream) {
        stream.getTracks().forEach(track => track.stop());
        if (photoNum === 1) {
            currentStream1 = null;
        }
    }
    
    document.getElementById(previewId).style.display = 'none';
}

async function switchCamera(photoNum) {
    const devices = await getCameraDevices();
    if (devices.length < 2) {
        alert('No alternative camera found');
        return;
    }
    
    const currentId = photoNum === 1 ? currentDeviceId1 : null;
    const currentIndex = devices.findIndex(d => d.deviceId === currentId);
    const nextIndex = (currentIndex + 1) % devices.length;
    
    if (photoNum === 1) {
        currentDeviceId1 = devices[nextIndex].deviceId;
    }
    
    startCamera(photoNum);
}

function capturePhoto(photoNum) {
    const video = document.getElementById(`video${photoNum}`);
    const previewContainer = document.getElementById(`photoPreview${photoNum}`);
    const hiddenInput = document.getElementById(`photo${photoNum}_base64`);
    
    const canvas = document.createElement('canvas');
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    
    const context = canvas.getContext('2d');
    context.drawImage(video, 0, 0, canvas.width, canvas.height);
    
    const base64Image = canvas.toDataURL('image/jpeg', 0.9);
    
    hiddenInput.value = base64Image;
    
    previewContainer.innerHTML = `
        <img src="${base64Image}" style="max-width: 100%; max-height: 300px; border-radius: 15px; margin-top: 15px;">
        <button type="button" class="camera-btn danger" style="margin-top: 10px;" onclick="retakePhoto(${photoNum})">
            <i class="bi bi-arrow-repeat"></i> Retake
        </button>
    `;
    
    stopCamera(photoNum);
}

function retakePhoto(photoNum) {
    const previewContainer = document.getElementById(`photoPreview${photoNum}`);
    const hiddenInput = document.getElementById(`photo${photoNum}_base64`);
    
    previewContainer.innerHTML = '';
    hiddenInput.value = '';
    startCamera(photoNum);
}

// Permission status change handler
document.querySelectorAll('input[name="permission_status"]').forEach(radio => {
    radio.addEventListener('change', function() {
        const notAllowedContainer = document.getElementById('not_allowed_reason_container');
        const interestContainer = document.getElementById('interest_status_container');
        const contactSection = document.getElementById('contact_info_section');
        const notAllowedReason = document.getElementById('not_allowed_reason');
        const skipToStep4 = document.getElementById('skip_to_step4');
        const backButton = document.getElementById('backToStep3');
        
        if (this.value === 'NOT_ALLOWED') {
            // Show reason field
            notAllowedContainer.style.display = 'block';
            notAllowedReason.setAttribute('required', 'required');
            
            // Hide interest status and contact info (not needed when not allowed)
            interestContainer.style.display = 'none';
            contactSection.style.display = 'none';
            
            // Remove required attributes from hidden fields
            document.querySelectorAll('input[name="interest_status"]').forEach(r => r.removeAttribute('required'));
            document.getElementById('phone').removeAttribute('required');
            
            // Set flag to skip to step 4
            skipToStep4.value = '1';
            
            // Update back button to go to step 2
            if (backButton) {
                backButton.href = 'visit_add.php?step=2';
            }
            
        } else {
            // Hide reason field
            notAllowedContainer.style.display = 'none';
            notAllowedReason.removeAttribute('required');
            
            // Show interest status and contact info
            interestContainer.style.display = 'block';
            contactSection.style.display = 'block';
            
            // Add required attributes back
            document.querySelectorAll('input[name="interest_status"]').forEach(r => r.setAttribute('required', 'required'));
            document.getElementById('phone').setAttribute('required', 'required');
            
            // Reset skip flag
            skipToStep4.value = '0';
            
            // Update back button to go to step 3 (normal flow)
            if (backButton) {
                backButton.href = 'visit_add.php?step=3';
            }
        }
    });
});

// Form submission handler for step 2
document.getElementById('visitResponseForm')?.addEventListener('submit', function(e) {
    const permissionStatus = document.querySelector('input[name="permission_status"]:checked');
    
    if (!permissionStatus) {
        e.preventDefault();
        alert('Please select permission status');
        return;
    }
    
    if (permissionStatus.value === 'NOT_ALLOWED') {
        const reason = document.getElementById('not_allowed_reason').value.trim();
        if (!reason) {
            e.preventDefault();
            alert('Please provide reason for not allowing permission');
            return;
        }
    } else {
        // Validate required fields for GRANTED/PENDING
        const authorityPerson = document.getElementById('authority_person').value;
        const interestStatus = document.querySelector('input[name="interest_status"]:checked');
        const phone = document.getElementById('phone').value.trim();
        
        if (!authorityPerson) {
            e.preventDefault();
            alert('Please select who you met with');
            return;
        }
        
        if (!interestStatus) {
            e.preventDefault();
            alert('Please select interest status');
            return;
        }
        
        if (!phone) {
            e.preventDefault();
            alert('Please enter phone number');
            return;
        }
        
        if (phone.replace(/\D/g, '').length < 10) {
            e.preventDefault();
            alert('Phone number must be at least 10 digits');
            return;
        }
    }
});

// GPS Capture
document.getElementById('captureGps')?.addEventListener('click', function() {
    const gpsStatus = document.getElementById('gpsStatus');
    const accuracyWarning = document.getElementById('accuracyWarning');
    const latitude = document.getElementById('latitude');
    const longitude = document.getElementById('longitude');
    const accuracy = document.getElementById('accuracy');
    const gpsCapturedAt = document.getElementById('gps_captured_at');
    const submitBtn = document.getElementById('submitBtn');
    const gpsBtnText = document.getElementById('gpsBtnText');
    const gpsLoading = document.getElementById('gpsLoading');
    
    gpsStatus.innerHTML = '<i class="bi bi-hourglass-split"></i> Getting your location...';
    gpsStatus.style.background = '#cce5ff';
    gpsStatus.style.color = '#004085';
    gpsBtnText.innerText = 'Getting Location...';
    gpsLoading.style.display = 'inline-block';
    
    if (!navigator.geolocation) {
        gpsStatus.innerHTML = '<i class="bi bi-exclamation-triangle"></i> GPS not supported';
        gpsStatus.style.background = '#f8d7da';
        gpsStatus.style.color = '#721c24';
        gpsBtnText.innerText = '📍 Get Current Location';
        gpsLoading.style.display = 'none';
        return;
    }
    
    navigator.geolocation.getCurrentPosition(
        function(position) {
            const acc = position.coords.accuracy;
            
            latitude.value = position.coords.latitude.toFixed(7);
            longitude.value = position.coords.longitude.toFixed(7);
            accuracy.value = acc.toFixed(1) + 'm';
            gpsCapturedAt.value = new Date().toISOString().slice(0, 19).replace('T', ' ');
            
            if (acc <= 150) {
                gpsStatus.innerHTML = '<i class="bi bi-check-circle"></i> ✓ Location captured! Accuracy: ' + acc.toFixed(1) + 'm';
                gpsStatus.style.background = '#d4edda';
                gpsStatus.style.color = '#155724';
                accuracyWarning.style.display = 'none';
                submitBtn.disabled = false;
            } else {
                gpsStatus.innerHTML = '<i class="bi bi-exclamation-triangle"></i> ⚠ Accuracy too low: ' + acc.toFixed(1) + 'm (Required < 150m)';
                gpsStatus.style.background = '#fff3cd';
                gpsStatus.style.color = '#856404';
                accuracyWarning.style.display = 'block';
                accuracyWarning.className = 'accuracy-warning bad';
                accuracyWarning.innerHTML = '❌ Accuracy must be less than 150 meters. Current: ' + acc.toFixed(1) + 'm. Please try again in an open area.';
                submitBtn.disabled = true;
            }
            
            gpsBtnText.innerText = '📍 Location Captured';
            gpsLoading.style.display = 'none';
        },
        function(error) {
            let message = '';
            switch(error.code) {
                case error.PERMISSION_DENIED:
                    message = 'Please allow location access';
                    break;
                case error.POSITION_UNAVAILABLE:
                    message = 'Location unavailable';
                    break;
                case error.TIMEOUT:
                    message = 'Location timeout';
                    break;
                default:
                    message = 'GPS error';
            }
            
            gpsStatus.innerHTML = '<i class="bi bi-exclamation-triangle"></i> ✗ ' + message;
            gpsStatus.style.background = '#f8d7da';
            gpsStatus.style.color = '#721c24';
            submitBtn.disabled = true;
            gpsBtnText.innerText = '📍 Get Current Location';
            gpsLoading.style.display = 'none';
        },
        {
            enableHighAccuracy: true,
            timeout: 10000,
            maximumAge: 0
        }
    );
});

// File upload preview
document.getElementById('photo1')?.addEventListener('change', function(e) {
    if (e.target.files && e.target.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const previewContainer = document.getElementById('photoPreview1');
            previewContainer.innerHTML = `
                <img src="${e.target.result}" style="max-width: 100%; max-height: 300px; border-radius: 15px; margin-top: 15px;">
            `;
            document.getElementById('photo1_base64').value = '';
        };
        reader.readAsDataURL(e.target.files[0]);
    }
});

// Form validation for step 4
document.getElementById('visitForm')?.addEventListener('submit', function(e) {
    const photo1Base64 = document.getElementById('photo1_base64').value;
    const photo1File = document.getElementById('photo1').files.length;
    const declaration = document.getElementById('self_declaration');
    
    if (!photo1Base64 && !photo1File) {
        e.preventDefault();
        alert('Please take or upload your selfie with school name board');
        return;
    }
    
    if (!declaration.checked) {
        e.preventDefault();
        alert('Please accept the self declaration');
        return;
    }
});

// Update back button based on permission status
document.addEventListener('DOMContentLoaded', function() {
    const permissionNotAllowed = document.querySelector('input[name="permission_status"][value="NOT_ALLOWED"]');
    const backButton = document.getElementById('backToStep3');
    
    if (permissionNotAllowed && permissionNotAllowed.checked && backButton) {
        backButton.href = 'visit_add.php?step=2';
    }
});
</script>

<?php require_once __DIR__ . "/partials/footer.php"; ?>