<?php
/**
 * JV Overseas Education - Student Visa Management
 * Updated with proper syntax and error handling
 */
session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Authentication check
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'student') {
    header('Location: student-login.php');
    exit;
}

// Get student data
$stmt = $pdo->prepare("SELECT s.*, u.email, 
                      CONCAT(c.first_name, ' ', c.last_name) as counselor_name,
                      c.id as counselor_id
                      FROM students s 
                      LEFT JOIN counselors c ON s.assigned_counselor_id = c.id
                      JOIN users u ON s.id = u.id 
                      WHERE s.id = ?");
$stmt->execute([$_SESSION['user_id']]);
$student = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$student) {
    die("Student profile not found.");
}

// Get visa applications
$visa_applications = $pdo->prepare("SELECT va.*, co.name as country_name, co.code as country_code
                                   FROM visa_applications va
                                   JOIN countries co ON va.country_id = co.id
                                   WHERE va.student_id = ?
                                   ORDER BY va.created_at DESC");
$visa_applications->execute([$_SESSION['user_id']]);
$visa_applications = $visa_applications->fetchAll();

// Get visa checklist for countries
$visa_checklist = [];
foreach ($visa_applications as $visa) {
    $checklist = $pdo->prepare("SELECT * FROM visa_checklist 
                               WHERE country_id = ? AND is_required = 1
                               ORDER BY document_name");
    $checklist->execute([$visa['country_id']]);
    $visa_checklist[$visa['id']] = $checklist->fetchAll();
}

// Get visa documents
$visa_documents = [];
foreach ($visa_applications as $visa) {
    $docs = $pdo->prepare("SELECT * FROM visa_documents 
                          WHERE visa_application_id = ?
                          ORDER BY created_at DESC");
    $docs->execute([$visa['id']]);
    $visa_documents[$visa['id']] = $docs->fetchAll();
}

$error = '';
$success = '';
$upload_dir = 'uploads/visa/';

// Ensure upload directory exists
if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

// Handle new visa application
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['apply_visa'])) {
    $country_id = $_POST['country_id'] ?? '';
    
    if (!empty($country_id)) {
        try {
            // Check if already has application for this country
            $stmt = $pdo->prepare("SELECT id FROM visa_applications 
                                  WHERE student_id = ? AND country_id = ?");
            $stmt->execute([$_SESSION['user_id'], $country_id]);
            
            if (!$stmt->fetch()) {
                $stmt = $pdo->prepare("INSERT INTO visa_applications (
                    student_id, country_id, status, application_date, expected_decision_date, counselor_id, created_at
                ) VALUES (?, ?, 'not_started', NOW(), DATE_ADD(NOW(), INTERVAL 60 DAY), ?, NOW())");
                
                $stmt->execute([$_SESSION['user_id'], $country_id, $student['counselor_id']]);
                
                // Create notification for counselor
                if ($student['counselor_id']) {
                    $pdo->prepare("INSERT INTO notifications (
                        user_id, title, message, is_read, notification_type, created_at
                    ) VALUES (?, ?, ?, 0, 'visa', NOW())")->execute([
                        $student['counselor_id'],
                        "New Visa Application",
                        "Student {$_SESSION['first_name']} {$_SESSION['last_name']} has started a visa application for " . 
                        $pdo->query("SELECT name FROM countries WHERE id = $country_id")->fetchColumn()
                    ]);
                }
                
                $_SESSION['success'] = "Visa application started successfully!";
                header("Location: student-visa.php");
                exit;
                
            } else {
                $error = "You already have a visa application for this country.";
            }
        } catch (Exception $e) {
            $error = "Failed to create visa application. Please try again.";
        }
    } else {
        $error = "Please select a country.";
    }
}

// Handle document upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_visa_document'])) {
    $visa_app_id = $_POST['visa_app_id'] ?? '';
    $document_type = $_POST['document_type'] ?? '';
    $notes = trim($_POST['notes'] ?? '');
    
    if (empty($visa_app_id) || empty($document_type) || empty($_FILES['document_file']['name'])) {
        $error = "Please fill all required fields.";
    } elseif (!in_array($visa_app_id, array_column($visa_applications, 'id'))) {
        $error = "Invalid visa application selected.";
    } else {
        // Validate file
        $file_name = $_FILES['document_file']['name'];
        $file_tmp = $_FILES['document_file']['tmp_name'];
        $file_size = $_FILES['document_file']['size'];
        $file_error = $_FILES['document_file']['error'];
        
        // Get file extension
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        $allowed_exts = ['pdf', 'jpg', 'jpeg', 'png'];
        
        if ($file_error !== UPLOAD_ERR_OK) {
            $error = "File upload error occurred.";
        } elseif ($file_size > 10 * 1024 * 1024) { // 10MB limit
            $error = "File size must be less than 10MB.";
        } elseif (!in_array($file_ext, $allowed_exts)) {
            $error = "Only PDF, JPG, and PNG files are allowed.";
        } else {
            // Create upload directory if it doesn't exist
            $upload_dir = 'uploads/visa/';
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            // Generate unique filename (FIXED: was missing space/line break)
            $unique_name = $_SESSION['user_id'] . '_visa_' . time() . '_' . bin2hex(random_bytes(8)) . '.' . $file_ext;
            $file_path = $upload_dir . $unique_name;  // This was incorrectly concatenated
            
            // Move uploaded file
            if (move_uploaded_file($file_tmp, $file_path)) {
                try {
                    // Insert into database
                    $stmt = $pdo->prepare("INSERT INTO visa_documents (
                        visa_application_id, document_type, file_path, status, notes, created_at
                    ) VALUES (?, ?, ?, 'uploaded', ?, NOW())");
                    
                    $stmt->execute([$visa_app_id, $document_type, $file_path, $notes]);
                    
                    $_SESSION['success'] = "Document uploaded successfully!";
                    header("Location: student-visa.php");
                    exit;
                    
                    // Update visa application status
                    $pdo->prepare("UPDATE visa_applications SET status = 'document_collection' 
                                  WHERE id = ? AND status = 'not_started'")->execute([$visa_app_id]);
                    
                } catch (Exception $e) {
                    // Remove file if database insert fails
                    if (file_exists($file_path)) {
                        unlink($file_path);
                    }
                    $error = "Failed to save document information. Please try again.";
                }
            } else {
                $error = "Failed to save uploaded file. Please try again.";
            }
        }
    }
}

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: student-dashboard.php');
    exit;
}

// Display success message from session if exists
$success = $_SESSION['success'] ?? '';
unset($_SESSION['success']);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Visa Applications - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .visa-status {
            padding: 8px 15px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.9em;
        }
        .status-not_started {
            background: #f8f9fa;
            color: #6c757d;
        }
        .status-document_collection {
            background: #fff3cd;
            color: #856404;
        }
        .status-application_submitted {
            background: #d1ecf1;
            color: #0c5460;
        }
        .status-biometrics_completed {
            background: #bee5eb;
            color: #0c5460;
        }
        .status-under_review {
            background: #cce5ff;
            color: #004085;
        }
        .status-approved {
            background: #d4edda;
            color: #155724;
        }
        .status-rejected {
            background: #f8d7da;
            color: #721c24;
        }
        .checklist-item {
            padding: 10px 15px;
            margin-bottom: 5px;
            border-radius: 5px;
            border-left: 4px solid #3fb7fe;
        }
        .checklist-item.completed {
            background: #d4edda;
            border-left-color: #155724;
        }
        .checklist-item.pending {
            background: #fff3cd;
        }
        .document-item {
            border-bottom: 1px solid #eee;
            padding: 12px 0;
        }
        .document-item:last-child {
            border-bottom: none;
        }
        .file-icon {
            font-size: 1.8em;
            color: #3fb7fe;
        }
        .timeline {
            position: relative;
            padding: 20px 0;
        }
        .timeline::before {
            content: '';
            position: absolute;
            left: 30px;
            top: 0;
            bottom: 0;
            width: 2px;
            background: #e9ecef;
        }
        .timeline-item {
            position: relative;
            margin-bottom: 20px;
            padding-left: 60px;
        }
        .timeline-item::before {
            content: '';
            position: absolute;
            left: 25px;
            top: 8px;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #fff;
            border: 2px solid #3fb7fe;
        }
        .timeline-item.current::before {
            background: #3fb7fe;
        }
        .timeline-date {
            color: #6c757d;
            font-size: 0.9em;
        }
        .custom-file-label::after {
            content: "Browse";
        }
    </style>
</head>
<body>

<?php include 'student-navbar.php'; ?>

<div class="container py-5">
    <div class="section-title position-relative mb-4">
        <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Visa Applications</h6>
        <h1 class="display-5">Manage Your Visa Process</h1>
    </div>

    <?php if (isset($error)): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    
    <?php if (!empty($success)): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>

    <div class="row">
        <div class="col-lg-8">
            <!-- Start New Application -->
            <div class="bg-white p-4 rounded mb-4">
                <h5 class="mb-3">Start New Visa Application</h5>
                
                <form method="POST" class="d-flex">
                    <div class="flex-grow-1 mr-2">
                        <select name="country_id" class="form-control" required>
                            <option value="">Select Country</option>
                            <?php
                            $countries = $pdo->query("SELECT id, name FROM countries ORDER BY name");
                            while ($country = $countries->fetch()): ?>
                                <option value="<?= htmlspecialchars($country['id']) ?>">
                                    <?= htmlspecialchars($country['name']) ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <button type="submit" name="apply_visa" class="btn btn-primary">
                        <i class="fas fa-passport"></i> Start Application
                    </button>
                </form>
                
                <small class="text-muted mt-2">Select your destination country to begin the visa application process.</small>
            </div>

            <!-- Visa Applications List -->
            <?php if (empty($visa_applications)): ?>
                <div class="text-center py-5 bg-light rounded">
                    <i class="fas fa-passport fa-3x text-muted mb-3"></i>
                    <p>You haven't started any visa applications yet.</p>
                    <p class="small">Your visa journey begins after you receive an admission offer.</p>
                </div>
            <?php else: ?>
                <?php foreach ($visa_applications as $visa): ?>
                <div class="bg-white p-4 rounded mb-4">
                    <div class="d-flex justify-content-between align-items-start mb-3">
                        <div>
                            <h5><?= htmlspecialchars($visa['country_name']) ?> 
                               <span class="visa-status status-<?= $visa['status'] ?>">
                                   <?= ucfirst(str_replace('_', ' ', $visa['status'])) ?>
                               </span>
                            </h5>
                            <p class="text-muted mb-1">
                                <i class="far fa-calendar-alt"></i> 
                                Started: <?= date('M j, Y', strtotime($visa['application_date'])) ?>
                            </p>
                            <?php if ($visa['expected_decision_date']): ?>
                            <p class="text-muted mb-0">
                                <i class="far fa-clock"></i> 
                                Expected Decision: <?= date('M j, Y', strtotime($visa['expected_decision_date'])) ?>
                            </p>
                            <?php endif; ?>
                        </div>
                        <div class="text-right">
                            <p class="mb-1">
                                <strong>Visa Type:</strong> 
                                <?= $visa['visa_type'] ? htmlspecialchars($visa['visa_type']) : 'Student Visa' ?>
                            </p>
                            <?php if ($visa['visa_number']): ?>
                            <p class="mb-0">
                                <strong>Visa #:</strong> <?= htmlspecialchars($visa['visa_number']) ?>
                            </p>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Timeline -->
                    <div class="timeline mb-4">
                        <div class="timeline-item <?= ($visa['status'] === 'not_started') ? 'current' : '' ?>">
                            <h6>Application Initiated</h6>
                            <div class="timeline-date"><?= date('M j', strtotime($visa['application_date'])) ?></div>
                        </div>
                        <div class="timeline-item <?= (in_array($visa['status'], ['document_collection', 'application_submitted', 'biometrics_completed', 'under_review', 'approved', 'rejected'])) ? 'current' : '' ?>">
                            <h6>Document Collection</h6>
                            <div class="timeline-date">
                                <?php 
                                $docs = $visa_documents[$visa['id']] ?? [];
                                $completed = count(array_filter($docs, function($d) { return $d['status'] === 'approved'; }));
                                echo $completed . '/' . count($docs) . ' documents approved';
                                ?>
                            </div>
                        </div>
                        <div class="timeline-item <?= (in_array($visa['status'], ['application_submitted', 'biometrics_completed', 'under_review', 'approved', 'rejected'])) ? 'current' : '' ?>">
                            <h6>Application Submitted</h6>
                            <div class="timeline-date">Pending</div>
                        </div>
                        <div class="timeline-item <?= (in_array($visa['status'], ['biometrics_completed', 'under_review', 'approved', 'rejected'])) ? 'current' : '' ?>">
                            <h6>Biometrics Completed</h6>
                            <div class="timeline-date">Pending</div>
                        </div>
                        <div class="timeline-item <?= (in_array($visa['status'], ['under_review', 'approved', 'rejected'])) ? 'current' : '' ?>">
                            <h6>Under Review</h6>
                            <div class="timeline-date">Pending</div>
                        </div>
                        <div class="timeline-item <?= (in_array($visa['status'], ['approved', 'rejected'])) ? 'current' : '' ?>">
                            <h6>Decision</h6>
                            <div class="timeline-date">Pending</div>
                        </div>
                    </div>

                    <!-- Checklist -->
                    <div class="bg-light p-3 rounded mb-3">
                        <h6><i class="fas fa-check-square"></i> Required Documents</h6>
                        <?php if (empty($visa_checklist[$visa['id']])): ?>
                            <p class="small text-muted">Checklist loading...</p>
                        <?php else: ?>
                            <div class="row">
                                <?php foreach ($visa_checklist[$visa['id']] as $item): ?>
                                <div class="col-md-6 mb-2">
                                    <div class="checklist-item <?= 
                                        in_array($item['document_name'], array_column($visa_documents[$visa['id']] ?? [], 'document_type')) 
                                        ? 'completed' : 'pending' 
                                    ?>">
                                        <i class="fas <?= 
                                            in_array($item['document_name'], array_column($visa_documents[$visa['id']] ?? [], 'document_type')) 
                                            ? 'fa-check-circle text-success' : 'fa-circle text-warning' 
                                        ?> mr-2"></i>
                                        <?= htmlspecialchars($item['document_name']) ?>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>

                    <!-- Upload Document Form -->
                    <div class="border p-3 rounded mb-3">
                        <h6><i class="fas fa-upload"></i> Upload Document</h6>
                        <form method="POST" enctype="multipart/form-data">
                            <input type="hidden" name="visa_app_id" value="<?= $visa['id'] ?>">
                            <div class="row">
                                <div class="col-md-5 mb-2">
                                    <select name="document_type" class="form-control" required>
                                        <option value="">Select Document</option>
                                        <?php if (!empty($visa_checklist[$visa['id']])): ?>
                                            <?php foreach ($visa_checklist[$visa['id']] as $item): ?>
                                            <option value="<?= htmlspecialchars($item['document_name']) ?>">
                                                <?= htmlspecialchars($item['document_name']) ?>
                                            </option>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            <option value="passport">Passport Copy</option>
                                            <option value="financial_statement">Financial Statement</option>
                                            <option value="admission_letter">Admission Letter</option>
                                            <option value="other">Other Document</option>
                                        <?php endif; ?>
                                    </select>
                                </div>
                                <div class="col-md-5 mb-2">
                                    <div class="custom-file">
                                        <input type="file" class="custom-file-input" name="document_file" id="documentFile<?= $visa['id'] ?>" required>
                                        <label class="custom-file-label" for="documentFile<?= $visa['id'] ?>">Choose file...</label>
                                    </div>
                                </div>
                                <div class="col-md-2 mb-2">
                                    <button type="submit" name="upload_visa_document" class="btn btn-primary btn-block">Upload</button>
                                </div>
                            </div>
                            <div class="form-group mt-2">
                                <textarea name="notes" class="form-control" placeholder="Add notes (optional)"></textarea>
                            </div>
                            <small class="text-muted">Accepted formats: PDF, JPG, PNG (max 10MB)</small>
                        </form>
                    </div>

                    <!-- Uploaded Documents -->
                    <?php if (!empty($visa_documents[$visa['id']])): ?>
                    <h6 class="mb-3"><i class="fas fa-folder"></i> Uploaded Documents</h6>
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Document</th>
                                    <th>Status</th>
                                    <th>Uploaded</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($visa_documents[$visa['id']] as $doc): ?>
                                <tr>
                                    <td>
                                        <i class="fas fa-file-alt file-icon mr-2"></i>
                                        <?= htmlspecialchars($doc['document_type']) ?>
                                    </td>
                                    <td>
    <span class="badge badge-<?= 
        $doc['status'] === 'approved' ? 'success' : 
        ($doc['status'] === 'uploaded' ? 'info' : 'warning')
    ?>"><?= ucfirst($doc['status']) ?></span>
</td>
                                    <td><?= date('M j, Y', strtotime($doc['created_at'])) ?></td>
                                    <td>
                                        <a href="<?= htmlspecialchars($doc['file_path']) ?>" 
                                           class="btn btn-sm btn-primary" target="_blank">
                                            <i class="fas fa-eye"></i> View
                                        </a>
                                        <?php if ($doc['notes']): ?>
                                        <button class="btn btn-sm btn-info" title="<?= htmlspecialchars($doc['notes']) ?>">
                                            <i class="fas fa-info-circle"></i>
                                        </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <div class="col-lg-4">
            <div class="bg-light p-4 rounded">
                <h6><i class="fas fa-info-circle"></i> Visa Process Overview</h6>
                <ol class="small">
                    <li>Receive admission offer from university</li>
                    <li>Start visa application in your portal</li>
                    <li>Collect required documents</li>
                    <li>Submit application to embassy</li>
                    <li>Attend biometrics appointment</li>
                    <li>Wait for decision (4-8 weeks)</li>
                    <li>Receive visa and prepare for travel</li>
                </ol>
                
                <hr>
                
                <h6><i class="fas fa-clock"></i> Processing Times</h6>
                <ul class="small">
                    <li><strong>UK:</strong> 3-6 weeks</li>
                    <li><strong>USA:</strong> 6-8 weeks</li>
                    <li><strong>Canada:</strong> 4-6 weeks</li>
                    <li><strong>Australia:</strong> 4-8 weeks</li>
                    <li><strong>Germany:</strong> 3-4 weeks</li>
                </ul>
                
                <hr>
                
                <h6><i class="fas fa-question-circle"></i> Need Help?</h6>
                <p class="small mb-1">Contact your counselor:</p>
                <?php if ($student['counselor_name']): ?>
                    <p class="font-weight-bold"><?= htmlspecialchars($student['counselor_name']) ?></p>
                <?php else: ?>
                    <p class="font-weight-bold">Not assigned yet</p>
                <?php endif; ?>
                <p class="small">+256 788 289 235</p>
                <p class="small">Email: <?= htmlspecialchars($student['email']) ?></p>
            </div>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
<script>
    // Update file input label with selected filename
    $('.custom-file-input').on('change', function() {
        let fileName = $(this).val().split('\\').pop();
        $(this).next('.custom-file-label').addClass("selected").html(fileName);
    });
    
    // Form submission confirmation
    $('form').on('submit', function(e) {
        if ($(this).find('[type="submit"][name="upload_visa_document"]').length) {
            const docType = $('select[name="document_type"]').val();
            if (docType) {
                if (!confirm(`You are about to upload a ${docType}. Continue?`)) {
                    e.preventDefault();
                }
            }
        }
    });
</script>
</body>
</html>