<?php
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'] !== 'admin') {
    header('Location: admin-login.php');
    exit;
}

// Get admin data
$stmt = $pdo->prepare("SELECT a.*, u.email FROM admins a JOIN users u ON a.id = u.id WHERE a.id = ?");
$stmt->execute([$_SESSION['user_id']]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin) {
    die("Admin profile not found.");
}

$error = '';
$success = '';

// Get student ID if provided in URL
$student_id = $_GET['student_id'] ?? null;

// Handle application creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_application'])) {
    $student_id = $_POST['student_id'] ?? null;
    $program_id = $_POST['program_id'] ?? null;
    $counselor_id = $_POST['counselor_id'] ?? $_SESSION['user_id'];
    $application_status = $_POST['application_status'] ?? 'draft';
    $submission_date = $_POST['submission_date'] ?? null;
    $application_fee_paid = isset($_POST['application_fee_paid']) ? 1 : 0;
    $fee_payment_date = $_POST['fee_payment_date'] ?? null;
    $fee_amount = $_POST['fee_amount'] ?? null;
    $scholarship_awarded = $_POST['scholarship_awarded'] ?? null;
    $notes = $_POST['notes'] ?? '';
    
    // Validate form data
    if (!$student_id || !$program_id) {
        $error = "Student and program are required.";
    } else {
        try {
            // Check if student exists
            $stmt = $pdo->prepare("SELECT id FROM students WHERE id = ?");
            $stmt->execute([$student_id]);
            if (!$stmt->fetch()) {
                $error = "Invalid student selected.";
            }
            
            // Check if program exists
            $stmt = $pdo->prepare("SELECT id, tuition_fee, tuition_fee_currency FROM programs WHERE id = ?");
            $stmt->execute([$program_id]);
            $program = $stmt->fetch();
            if (!$program) {
                $error = "Invalid program selected.";
            }
            
            if (!$error) {
                // Start transaction
                $pdo->beginTransaction();
                
                // Create application
                $stmt = $pdo->prepare("INSERT INTO applications (
                    student_id, program_id, counselor_id, application_status, submission_date,
                    application_fee_paid, fee_payment_date, fee_amount, scholarship_awarded, notes, created_at, updated_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");
                
                $stmt->execute([
                    $student_id, $program_id, $counselor_id, $application_status, $submission_date,
                    $application_fee_paid, $fee_payment_date, $fee_amount, $scholarship_awarded, $notes
                ]);
                
                $application_id = $pdo->lastInsertId();
                
                // If application is submitted, create an invoice for the application fee if not already paid
                if ($application_status === 'submitted' && !$application_fee_paid && $fee_amount) {
                    $stmt = $pdo->prepare("INSERT INTO invoices (
                        student_id, title, description, amount, currency, due_date, status, created_at, updated_at
                    ) VALUES (?, ?, ?, ?, ?, DATE_ADD(NOW(), INTERVAL 14 DAY), 'unpaid', NOW(), NOW())");
                    
                    $stmt->execute([
                        $student_id,
                        "Application Fee",
                        "Application fee for {$program['tuition_fee_currency']} {$fee_amount} to {$program_id}",
                        $fee_amount,
                        $program['tuition_fee_currency'],
                    ]);
                }
                
                // Log the activity
                $pdo->prepare("INSERT INTO activities (
                    user_id, activity_type, description, created_at
                ) VALUES (?, ?, ?, NOW())")->execute([
                    $_SESSION['user_id'],
                    "application_created",
                    "Admin {$_SESSION['first_name']} {$_SESSION['last_name']} created application for student {$student_id} to program {$program_id}"
                ]);
                
                // Create notification for student
                $pdo->prepare("INSERT INTO notifications (
                    user_id, title, message, is_read, notification_type, created_at
                ) VALUES (?, ?, ?, 0, 'application', NOW())")->execute([
                    $student_id,
                    "New Application Created",
                    "A new application has been created for you by an administrator"
                ]);
                
                // If counselor is assigned, create notification for counselor
                if ($counselor_id && $counselor_id != $_SESSION['user_id']) {
                    $pdo->prepare("INSERT INTO notifications (
                        user_id, title, message, is_read, notification_type, created_at
                    ) VALUES (?, ?, ?, 0, 'application', NOW())")->execute([
                        $counselor_id,
                        "New Application Assigned",
                        "A new application has been created and assigned to you by an administrator"
                    ]);
                }
                
                // Commit transaction
                $pdo->commit();
                
                $success = "Application created successfully!";
                
                // Redirect to avoid resubmission
                header("Location: admin-application-review.php?id={$application_id}&created=1");
                exit;
            }
        } catch (Exception $e) {
            $pdo->rollback();
            $error = "Failed to create application. Please try again. Error: " . $e->getMessage();
        }
    }
}

// Get students for dropdown - Fixed: profile_photo is in the students table, not users table
$students = $pdo->query("SELECT s.id, s.first_name, s.last_name, s.status, s.profile_photo,
                        u.email
                        FROM students s
                        JOIN users u ON s.id = u.id
                        ORDER BY s.last_name, s.first_name")->fetchAll();

// Get programs for dropdown
$programs = $pdo->query("SELECT p.id, p.name, p.degree_level, u.name as university_name
                        FROM programs p
                        JOIN universities u ON p.university_id = u.id
                        ORDER BY u.name, p.name")->fetchAll();

// Get counselors for dropdown
$counselors = $pdo->query("SELECT c.id, c.first_name, c.last_name
                         FROM counselors c
                         ORDER BY c.last_name, c.first_name")->fetchAll();

// If student_id is provided, get student data
$selected_student = null;
if ($student_id) {
    $stmt = $pdo->prepare("SELECT s.*, u.email FROM students s JOIN users u ON s.id = u.id WHERE s.id = ?");
    $stmt->execute([$student_id]);
    $selected_student = $stmt->fetch();
}

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin-login.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Create Application - 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>
        .form-section {
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
        }
        .form-section:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }
        .section-title {
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #3fb7fe;
        }
        .student-info {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        .student-photo {
            width: 80px;
            height: 80px;
            object-fit: cover;
            border-radius: 50%;
            border: 3px solid #3fb7fe;
            margin-right: 15px;
        }
        .program-info {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
            display: none;
        }
        .university-logo {
            height: 60px;
            object-fit: contain;
            background: white;
            padding: 5px;
            border-radius: 5px;
            margin-right: 15px;
        }
        .fee-info {
            font-size: 0.9em;
            color: #6c757d;
        }
        .info-box {
            background: #f8f9fa;
            border-left: 4px solid #3fb7fe;
            padding: 15px;
            margin: 20px 0;
            border-radius: 5px;
        }
    </style>
</head>
<body>

<?php include 'admin-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">Application Management</h6>
        <h1 class="display-5">Create New Application</h1>
    </div>

    <?php if ($error): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    
    <?php if ($success): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
        <div class="text-center mb-4">
            <a href="admin-applications.php" class="btn btn-primary">View All Applications</a>
        </div>
    <?php else: ?>
        <form method="POST">
            <div class="form-section">
                <h5 class="section-title">Select Student</h5>
                
                <?php if ($selected_student): ?>
                <div class="student-info">
                    <div class="d-flex align-items-center">
                        <img src="<?= htmlspecialchars($selected_student['profile_photo'] ?: 'img/profile-placeholder.jpg') ?>" 
                             alt="<?= htmlspecialchars($selected_student['first_name']) ?>" class="student-photo">
                        <div>
                            <h5><?= htmlspecialchars($selected_student['first_name'] . ' ' . $selected_student['last_name']) ?></h5>
                            <p class="text-muted mb-0"><?= htmlspecialchars($selected_student['email']) ?></p>
                            <p class="text-muted mb-0">Status: <strong><?= ucfirst($selected_student['status']) ?></strong></p>
                        </div>
                    </div>
                </div>
                <input type="hidden" name="student_id" value="<?= $selected_student['id'] ?>">
                <?php else: ?>
                <div class="form-group">
                    <label>Student *</label>
                    <select name="student_id" class="form-control" id="studentSelect" required onchange="updateStudentInfo()">
                        <option value="">Select Student</option>
                        <?php foreach ($students as $s): ?>
                        <option value="<?= $s['id'] ?>" 
                                data-email="<?= htmlspecialchars($s['email']) ?>"
                                data-status="<?= htmlspecialchars($s['status']) ?>"
                                data-photo="<?= htmlspecialchars($s['profile_photo'] ?: 'img/profile-placeholder.jpg') ?>">
                            <?= htmlspecialchars($s['first_name'] . ' ' . $s['last_name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div id="studentInfo" class="student-info" style="display: none;">
                    <div class="d-flex align-items-center">
                        <img src="" alt="" class="student-photo" id="studentPhoto">
                        <div>
                            <h5 id="studentName"></h5>
                            <p class="text-muted mb-0">Email: <span id="studentEmail"></span></p>
                            <p class="text-muted mb-0">Status: <strong id="studentStatus"></strong></p>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
            
            <div class="form-section">
                <h5 class="section-title">Select Program</h5>
                <div class="form-group">
                    <label>Program *</label>
                    <select name="program_id" class="form-control" id="programSelect" required onchange="updateProgramInfo()">
                        <option value="">Select Program</option>
                        <?php foreach ($programs as $p): ?>
                        <option value="<?= $p['id'] ?>" 
                                data-university="<?= htmlspecialchars($p['university_name']) ?>"
                                data-level="<?= htmlspecialchars($p['degree_level']) ?>">
                            <?= htmlspecialchars($p['university_name'] . ' - ' . $p['degree_level'] . ': ' . $p['name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div id="programInfo" class="program-info">
                    <div class="d-flex align-items-center">
                        <img src="img/university-placeholder.png" alt="" class="university-logo" id="universityLogo">
                        <div>
                            <h5 id="universityName"></h5>
                            <p class="text-muted mb-0"><span id="degreeLevel"></span>: <span id="programName"></span></p>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="form-section">
                <h5 class="section-title">Application Details</h5>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>Counselor</label>
                        <select name="counselor_id" class="form-control">
                            <option value="<?= $_SESSION['user_id'] ?>">Me (<?= htmlspecialchars($admin['first_name'] . ' ' . $admin['last_name']) ?>)</option>
                            <?php foreach ($counselors as $c): ?>
                            <option value="<?= $c['id'] ?>" <?= ($c['id'] == $_SESSION['user_id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($c['first_name'] . ' ' . $c['last_name']) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label>Application Status *</label>
                        <select name="application_status" class="form-control" required>
                            <option value="draft">Draft</option>
                            <option value="submitted">Submitted</option>
                            <option value="under_review">Under Review</option>
                            <option value="interview_scheduled">Interview Scheduled</option>
                            <option value="accepted">Accepted</option>
                            <option value="conditionally_accepted">Conditionally Accepted</option>
                            <option value="rejected">Rejected</option>
                            <option value="withdrawn">Withdrawn</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label>Submission Date</label>
                    <input type="date" name="submission_date" class="form-control">
                </div>
                <div class="form-group">
                    <div class="custom-control custom-checkbox">
                        <input type="checkbox" class="custom-control-input" id="application_fee_paid" name="application_fee_paid">
                        <label class="custom-control-label" for="application_fee_paid">Application Fee Paid</label>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>Fee Payment Date</label>
                        <input type="date" name="fee_payment_date" class="form-control">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label>Fee Amount</label>
                        <div class="input-group">
                            <div class="input-group-prepend">
                                <span class="input-group-text">$</span>
                            </div>
                            <input type="number" name="fee_amount" class="form-control" step="0.01" min="0">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label>Scholarship Awarded</label>
                    <div class="input-group">
                        <div class="input-group-prepend">
                            <span class="input-group-text">$</span>
                        </div>
                        <input type="number" name="scholarship_awarded" class="form-control" step="0.01" min="0">
                    </div>
                </div>
                <div class="form-group">
                    <label>Notes</label>
                    <textarea name="notes" class="form-control" rows="4" placeholder="Internal notes about this application"></textarea>
                </div>
            </div>
            
            <div class="info-box">
                <h6><i class="fas fa-info-circle"></i> What Happens Next?</h6>
                <ul class="small">
                    <li>The student will be notified of the new application</li>
                    <li>If the application status is "Submitted", an invoice will be created for the application fee if not already paid</li>
                    <li>The assigned counselor will be notified if different from the creating admin</li>
                    <li>You can add application documents and notes after creating the application</li>
                </ul>
            </div>
            
            <div class="text-center">
                <button type="submit" name="create_application" class="btn btn-primary btn-lg px-5">Create Application</button>
            </div>
            
            <div class="text-center mt-3">
                <a href="admin-applications.php" class="btn btn-outline-primary">Cancel</a>
            </div>
        </form>
    <?php endif; ?>
</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 student info when student is selected
    function updateStudentInfo() {
        const select = document.getElementById('studentSelect');
        const selectedOption = select.options[select.selectedIndex];
        
        if (selectedOption.value) {
            document.getElementById('studentInfo').style.display = 'block';
            document.getElementById('studentPhoto').src = selectedOption.dataset.photo;
            document.getElementById('studentName').textContent = selectedOption.text;
            document.getElementById('studentEmail').textContent = selectedOption.dataset.email;
            document.getElementById('studentStatus').textContent = selectedOption.dataset.status;
        } else {
            document.getElementById('studentInfo').style.display = 'none';
        }
    }
    
    // Update program info when program is selected
    function updateProgramInfo() {
        const select = document.getElementById('programSelect');
        const selectedOption = select.options[select.selectedIndex];
        
        if (selectedOption.value) {
            document.getElementById('programInfo').style.display = 'block';
            document.getElementById('universityName').textContent = selectedOption.dataset.university;
            document.getElementById('degreeLevel').textContent = selectedOption.dataset.level;
            document.getElementById('programName').textContent = selectedOption.text.split(': ')[1];
        } else {
            document.getElementById('programInfo').style.display = 'none';
        }
    }
    
    // Initialize if a student was pre-selected
    <?php if ($selected_student): ?>
    document.addEventListener('DOMContentLoaded', function() {
        updateProgramInfo();
    });
    <?php endif; ?>
    
    // Form submission confirmation
    $('form').on('submit', function(e) {
        const studentSelect = $('#studentSelect');
        const programSelect = $('#programSelect');
        const studentName = studentSelect.find('option:selected').text();
        const programName = programSelect.find('option:selected').text();
        
        if (studentSelect.val() && programSelect.val() && 
            confirm(`You are about to create an application for ${studentName} to ${programName}. Continue?`)) {
            return true;
        } else {
            e.preventDefault();
        }
    });
    
    // Show/hide fee payment fields based on checkbox
    $('#application_fee_paid').on('change', function() {
        if ($(this).is(':checked')) {
            $('input[name="fee_payment_date"]').closest('.row').show();
            $('input[name="fee_amount"]').closest('.row').show();
        } else {
            $('input[name="fee_payment_date"]').closest('.row').hide();
            $('input[name="fee_amount"]').closest('.row').hide();
        }
    }).trigger('change');
</script>
</body>
</html>