<?php
session_start();
include "dbconnect.php";

// Check if user is logged in (optional, depends on your setup)
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

// Get the visa ID from GET
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    die('Invalid ID.');
}
$id = (int)$_GET['id'];

// Fetch existing visa record with applicant info
$sql = "SELECT vm.*, ja.name AS applicant_name, ja.passport_no 
        FROM visa_management vm 
        JOIN job_applicants ja ON vm.applicant_id = ja.id 
        WHERE vm.id = ?";
$stmt = $con->prepare($sql);
$stmt->bind_param('i', $id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    die('Record not found.');
}

$row = $result->fetch_assoc();

// Initialize variables for form fields
$visa_status = $row['visa_status'];
$visa_type = $row['visa_type'];
$visa_issue_date = $row['visa_issue_date'];
$visa_expiry_date = $row['visa_expiry_date'];
$job_country = $row['job_country'];
$reference = $row['reference'];
$current_file = $row['visa_upload'];
$applicant_name = $row['applicant_name'];
$passport_no = $row['passport_no'];

$errors = [];
$success = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitize inputs
    $visa_status = trim($_POST['visa_status']);
    $visa_type = trim($_POST['visa_type']);
    $visa_issue_date = trim($_POST['visa_issue_date']);
    $visa_expiry_date = trim($_POST['visa_expiry_date']);
    $job_country = trim($_POST['job_country']);
    $reference = trim($_POST['reference']);

    // Basic validation
    if (empty($visa_status)) {
        $errors[] = "Visa status is required.";
    }
    if (empty($visa_type)) {
        $errors[] = "Visa type is required.";
    }
    if (empty($visa_issue_date)) {
        $errors[] = "Visa issue date is required.";
    }
    if (empty($visa_expiry_date)) {
        $errors[] = "Visa expiry date is required.";
    }
    if (empty($job_country)) {
        $errors[] = "Job country is required.";
    }
    if (empty($reference)) {
        $errors[] = "Agent reference is required.";
    }

    // Handle file upload if a new file is provided
    $upload_dir = 'uploads/visa_docs/';
    $new_file_path = $current_file; // default: keep old file

    if (isset($_FILES['visa_upload']) && $_FILES['visa_upload']['error'] !== UPLOAD_ERR_NO_FILE) {
        $file = $_FILES['visa_upload'];

        // Validate file type (allow PDF, images)
        $allowed_types = ['application/pdf', 'image/jpeg', 'image/png'];
        if (!in_array($file['type'], $allowed_types)) {
            $errors[] = "Only PDF, JPG, and PNG files are allowed for upload.";
        }

        // Validate file size (max 5MB)
        if ($file['size'] > 5 * 1024 * 1024) {
            $errors[] = "File size must be less than 5 MB.";
        }

        if (empty($errors)) {
            // Create upload directory if not exists
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }

            // Generate unique filename
            $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
            $filename = 'visa_' . $id . '_' . time() . '.' . $ext;
            $target_path = $upload_dir . $filename;

            // Move uploaded file
            if (move_uploaded_file($file['tmp_name'], $target_path)) {
                // Delete old file if exists and different
                if ($current_file && file_exists($current_file) && $current_file !== $target_path) {
                    unlink($current_file);
                }
                $new_file_path = $target_path;
            } else {
                $errors[] = "Failed to upload file.";
            }
        }
    }

    // If no errors, update database
    if (empty($errors)) {
        $update_sql = "UPDATE visa_management SET visa_status = ?, visa_type = ?, visa_issue_date = ?, visa_expiry_date = ?, visa_upload = ?, job_country = ?, reference = ? WHERE id = ?";
        $stmt_update = $con->prepare($update_sql);
        $stmt_update->bind_param('sssssssi', $visa_status, $visa_type, $visa_issue_date, $visa_expiry_date, $new_file_path, $job_country, $reference, $id);

        if ($stmt_update->execute()) {
            $success = "Record updated successfully.";
            // Update current file variable so form shows correct link
            $current_file = $new_file_path;
        } else {
            $errors[] = "Failed to update record: " . $con->error;
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Edit Visa Record</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet" />
    <style>
        body {
            background: #f8f9fa;
            padding: 20px;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .container {
            max-width: 700px;
            background: white;
            padding: 25px;
            border-radius: 8px;
            box-shadow: 0 0 15px rgb(0 0 0 / 0.1);
        }
        h2 {
            color: #198754;
            margin-bottom: 25px;
            font-weight: 700;
            text-align: center;
        }
        .form-label {
            font-weight: 600;
        }
        .btn-primary, .btn-secondary {
            border-radius: 0.5rem;
            font-weight: 600;
        }
        .alert {
            font-weight: 600;
        }
        .file-info {
            font-size: 0.9rem;
            color: #555;
            margin-top: 6px;
        }
    </style>
</head>
<body>
<div class="container">
    <h2>Edit Visa Record for <?= htmlspecialchars($applicant_name) ?> (Passport: <?= htmlspecialchars($passport_no) ?>)</h2>

    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger">
            <ul class="mb-0">
                <?php foreach ($errors as $e): ?>
                    <li><?= htmlspecialchars($e) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <?php if ($success): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>

    <form method="post" enctype="multipart/form-data" novalidate>
        <div class="mb-3">
            <label for="visa_status" class="form-label">Visa Status</label>
            <input type="text" name="visa_status" id="visa_status" class="form-control" required value="<?= htmlspecialchars($visa_status) ?>">
        </div>
        <div class="mb-3">
            <label for="visa_type" class="form-label">Visa Type</label>
            <input type="text" name="visa_type" id="visa_type" class="form-control" required value="<?= htmlspecialchars($visa_type) ?>">
        </div>
        <div class="mb-3">
            <label for="visa_issue_date" class="form-label">Visa Issue Date</label>
            <input type="date" name="visa_issue_date" id="visa_issue_date" class="form-control" required value="<?= htmlspecialchars($visa_issue_date) ?>">
        </div>
        <div class="mb-3">
            <label for="visa_expiry_date" class="form-label">Visa Expiry Date</label>
            <input type="date" name="visa_expiry_date" id="visa_expiry_date" class="form-control" required value="<?= htmlspecialchars($visa_expiry_date) ?>">
        </div>
        <div class="mb-3">
            <label for="job_country" class="form-label">Job Country</label>
            <input type="text" name="job_country" id="job_country" class="form-control" required value="<?= htmlspecialchars($job_country) ?>">
        </div>
        <div class="mb-3">
            <label for="reference" class="form-label">Agent Reference</label>
            <input type="text" name="reference" id="reference" class="form-control" required value="<?= htmlspecialchars($reference) ?>">
        </div>

        <div class="mb-3">
            <label for="visa_upload" class="form-label">Visa Document Upload (PDF, JPG, PNG) <small>(Optional)</small></label>
            <input type="file" name="visa_upload" id="visa_upload" class="form-control" accept=".pdf,.jpg,.jpeg,.png">
            <?php if ($current_file && file_exists($current_file)): ?>
                <div class="file-info mt-1">
                    Current file: <a href="<?= htmlspecialchars($current_file) ?>" target="_blank" rel="noopener noreferrer">View/Download</a>
                </div>
            <?php else: ?>
                <div class="file-info mt-1 text-muted">No file uploaded.</div>
            <?php endif; ?>
        </div>

        <div class="d-flex gap-2 justify-content-center">
            <button type="submit" class="btn btn-primary">
                <i class="bi bi-save"></i> Save Changes
            </button>
            <a href="visa_list.php" class="btn btn-secondary">
                <i class="bi bi-x-circle"></i> Cancel
            </a>
        </div>
    </form>
</div>

<!-- Bootstrap JS Bundle -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
