<?php
include 'includes/db.php';
include 'includes/header.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

if (!isset($_SESSION['current_application_program_id'])) {
    header("Location: application.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$program_id = $_SESSION['current_application_program_id'];

// Fetch Program Details
$sql_prog = "SELECT * FROM programs WHERE id = $program_id";
$res_prog = $conn->query($sql_prog);
$program = $res_prog->fetch_assoc();

// Fetch Personal Details
$sql_personal = "SELECT * FROM personal_details WHERE user_id = $user_id";
$res_personal = $conn->query($sql_personal);
$personal = $res_personal ? $res_personal->fetch_assoc() : null;

// Fetch Academic Records
$sql_academic = "SELECT * FROM academic_records WHERE user_id = $user_id";
$res_academic = $conn->query($sql_academic);

// Fetch Documents
$sql_docs = "SELECT * FROM documents WHERE user_id = $user_id";
$res_docs = $conn->query($sql_docs);

$error = "";
$success = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate voucher code first
    $voucher_code = isset($_POST['voucher_code']) ? trim($_POST['voucher_code']) : '';
    
    if (empty($voucher_code)) {
        $error = "Voucher code is required to submit application.";
    } else {
        // Check if voucher code is valid and active (simplified validation)
        $voucher_sql = "SELECT id FROM voucher_codes 
                       WHERE code = '$voucher_code' 
                       AND status = 'active' 
                       AND (expires_at IS NULL OR expires_at > NOW())";
        $voucher_result = $conn->query($voucher_sql);
        
        if ($voucher_result->num_rows == 0) {
            $error = "Invalid or expired voucher code. Please contact administration.";
        } else {
            // Voucher is valid, proceed with application submission
            $voucher_id = $voucher_result->fetch_assoc()['id'];
            
            // Update voucher to mark it as used and assign to this student/program
            $update_voucher_sql = "UPDATE voucher_codes 
                                  SET status = 'used', 
                                      student_id = $user_id, 
                                      program_id = $program_id, 
                                      used_at = NOW() 
                                  WHERE id = $voucher_id";
            $conn->query($update_voucher_sql);
            
            // Check if application already exists for this program
            $check_sql = "SELECT id FROM applications WHERE user_id = $user_id AND program_id = $program_id";
            $check_res = $conn->query($check_sql);

            if ($check_res->num_rows > 0) {
                $error = "You have already applied for this program.";
            } else {
                // Fetch current session and year from settings
                $current_session = 'Fall';
                $current_year = date('Y');
                $sess_sql = "SELECT setting_key, setting_value FROM system_settings WHERE setting_key IN ('current_session', 'current_academic_year')";
                $sess_res = $conn->query($sess_sql);
                if ($sess_res->num_rows > 0) {
                    while($row = $sess_res->fetch_assoc()) {
                        if($row['setting_key'] == 'current_session') $current_session = $row['setting_value'];
                        if($row['setting_key'] == 'current_academic_year') $current_year = $row['setting_value'];
                    }
                }

                $sql = "INSERT INTO applications (user_id, program_id, status, submission_date, session, academic_year, voucher_code) 
                        VALUES ($user_id, $program_id, 'Submitted', NOW(), '$current_session', '$current_year', '$voucher_code')";
                
                if ($conn->query($sql) === TRUE) {
                    unset($_SESSION['current_application_program_id']);
                    $success = "Application submitted successfully!";
                    // Redirect to dashboard after 2 seconds
                    header("refresh:2;url=dashboard.php");
                } else {
                    $error = "Error submitting application: " . $conn->error;
                }
            }
        }
    }
}
?>

<div class="dashboard-container">
    <div class="sidebar">
        <ul class="sidebar-menu">
            <li><a href="dashboard.php"><i class="fas fa-tachometer-alt" style="margin-right: 10px;"></i> Dashboard</a></li>
            <li><a href="application.php" class="active"><i class="fas fa-edit" style="margin-right: 10px;"></i> New Application</a></li>
            <li><a href="profile.php"><i class="fas fa-user" style="margin-right: 10px;"></i> My Profile</a></li>
            <li><a href="logout.php"><i class="fas fa-sign-out-alt" style="margin-right: 10px;"></i> Logout</a></li>
        </ul>
    </div>

    <div class="main-content">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Step 4: Review & Submit</h3>
            </div>
            
            <div style="margin-bottom: 20px;">
                <span class="badge badge-success">Step 1: Personal</span>
                <span class="badge badge-success">Step 2: Academic</span>
                <span class="badge badge-success">Step 3: Documents</span>
                <span class="badge badge-success">Step 4: Review</span>
            </div>

            <?php if($error): ?>
                <div class="alert alert-danger"><?php echo $error; ?></div>
            <?php endif; ?>
            <?php if($success): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i> <?php echo $success; ?>
                    <p>Redirecting to dashboard...</p>
                </div>
            <?php else: ?>

            <div style="margin-bottom: 30px;">
                <h3 style="color: var(--primary-color); border-bottom: 2px solid #eee; padding-bottom: 10px;">Program Details</h3>
                <p><strong>Program Name:</strong> <?php echo $program['program_name']; ?></p>
                <p><strong>Degree Level:</strong> <?php echo $program['degree_level']; ?></p>
            </div>

            <div style="margin-bottom: 30px;">
                <h3 style="color: var(--primary-color); border-bottom: 2px solid #eee; padding-bottom: 10px;">Personal Details <a href="application.php" style="font-size: 14px; float: right; color: var(--secondary-color);">Edit</a></h3>
                <?php if($personal): ?>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                        <p><strong>Father's Name:</strong> <?php echo $personal['father_name'] ?? 'Not provided'; ?></p>
                        <p><strong>Date of Birth:</strong> <?php echo $personal['dob'] ?? 'Not provided'; ?></p>
                        <p><strong>Gender:</strong> <?php echo $personal['gender'] ?? 'Not provided'; ?></p>
                        <p><strong>City:</strong> <?php echo $personal['city'] ?? 'Not provided'; ?></p>
                        <p><strong>Country:</strong> <?php echo $personal['country'] ?? 'Not provided'; ?></p>
                        <p><strong>Address:</strong> <?php echo $personal['address'] ?? 'Not provided'; ?></p>
                    </div>
                <?php else: ?>
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle"></i> Personal details not found. Please <a href="application.php">complete your personal details</a> before submitting the application.
                    </div>
                <?php endif; ?>
            </div>

            <div style="margin-bottom: 30px;">
                <h3 style="color: var(--primary-color); border-bottom: 2px solid #eee; padding-bottom: 10px;">Academic Records <a href="application_academic.php" style="font-size: 14px; float: right; color: var(--secondary-color);">Edit</a></h3>
                <table>
                    <thead>
                        <tr>
                            <th>Degree</th>
                            <th>Institute</th>
                            <th>Year</th>
                            <th>Marks</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while($row = $res_academic->fetch_assoc()): ?>
                        <tr>
                            <td><?php echo $row['degree_title']; ?></td>
                            <td><?php echo $row['institute']; ?></td>
                            <td><?php echo $row['passing_year']; ?></td>
                            <td><?php echo $row['obtained_marks']; ?> / <?php echo $row['total_marks']; ?></td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>

            <div style="margin-bottom: 30px;">
                <h3 style="color: var(--primary-color); border-bottom: 2px solid #eee; padding-bottom: 10px;">Documents <a href="application_documents.php" style="font-size: 14px; float: right; color: var(--secondary-color);">Edit</a></h3>
                <ul>
                    <?php while($row = $res_docs->fetch_assoc()): ?>
                        <li><?php echo $row['document_type']; ?> <i class="fas fa-check" style="color: green;"></i></li>
                    <?php endwhile; ?>
                </ul>
            </div>

            <form method="POST" action="" enctype="multipart/form-data" onsubmit="return confirm('Are you sure you want to submit? You cannot edit after submission.');">
                
                <div style="margin-bottom: 30px; background: #fff8e1; padding: 20px; border-radius: 8px; border: 1px solid #ffe0b2;">
                    <h3 style="color: var(--primary-color); margin-top: 0;"><i class="fas fa-ticket-alt"></i> Voucher Code</h3>
                    <p>Please enter the voucher code provided by the administration to submit your application.</p>
                    
                    <div class="form-group">
                        <label>Voucher Code <span style="color: red;">*</span></label>
                        <input type="text" name="voucher_code" class="form-control" required 
                               placeholder="Enter your voucher code" style="text-transform: uppercase; font-weight: bold;">
                        <small class="text-muted">Voucher code is required to submit application. Contact administration if you don't have one.</small>
                    </div>
                </div>

                <div style="margin-bottom: 30px; background: #f9f9f9; padding: 20px; border-radius: 8px;">
                    <h3 style="color: var(--primary-color); margin-top: 0;">Payment Details</h3>
                    <p>Please deposit the application processing fee of <strong>PKR 1,000</strong> in one of the following accounts and upload the receipt below.</p>
                    
                    <div style="background: #fff; padding: 15px; border: 1px solid #ddd; margin-bottom: 15px;">
                        <strong>Bank Name:</strong> Meezan Bank<br>
                        <strong>Account Title:</strong> University of Lahore Admission<br>
                        <strong>Account No:</strong> 0123-0102030405<br>
                    </div>

                    <div class="form-group">
                        <label>Upload Payment Receipt <span style="color: red;">*</span></label>
                        <input type="file" name="payment_receipt" class="form-control" required accept="image/*,.pdf">
                        <small class="text-muted">Supported formats: JPG, PNG, PDF</small>
                    </div>
                </div>

                <div class="form-group" style="margin-top: 30px; background: #fff8e1; padding: 15px; border: 1px solid #ffe0b2;">
                    <label style="display: flex; align-items: center;">
                        <input type="checkbox" required style="width: auto; margin-right: 10px;">
                        I hereby declare that the information provided is true and correct to the best of my knowledge. I understand that any false information may result in cancellation of admission.
                    </label>
                </div>

                <div style="text-align: right; margin-top: 20px;">
                    <a href="application_documents.php" class="btn-outline" style="padding: 10px 20px; margin-right: 10px; text-decoration: none;">Back</a>
                    <button type="submit" class="btn-primary" style="padding: 12px 40px; font-size: 1.1rem;"><i class="fas fa-paper-plane"></i> Submit Application</button>
                </div>
            </form>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
