<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], ['admin', 'system_admin', 'super_admin'])) {
    header("Location: login.php");
    exit();
}

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

if (!isset($_GET['id'])) {
    header("Location: index.php");
    exit();
}

$app_id = intval($_GET['id']);
$message = "";

// Handle Status Update
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Handle Application Edit
    if (isset($_POST['edit_application'])) {
        $full_name = $conn->real_escape_string($_POST['full_name']);
        $phone = $conn->real_escape_string($_POST['phone']);
        $cnic = $conn->real_escape_string($_POST['cnic']);
        $session = $conn->real_escape_string($_POST['session']);
        $academic_year = $conn->real_escape_string($_POST['academic_year']);
        
        // Update users table
        $sql_user = "UPDATE users u JOIN applications a ON u.id = a.user_id 
                    SET u.full_name = '$full_name', u.phone = '$phone', u.cnic = '$cnic' 
                    WHERE a.id = $app_id";
        
        // Update applications table
        $sql_app = "UPDATE applications SET session = '$session', academic_year = '$academic_year' WHERE id = $app_id";
        
        if ($conn->query($sql_user) === TRUE && $conn->query($sql_app) === TRUE) {
            $message = "Application details updated successfully!";
            // Refresh application data
            $result = $conn->query($sql);
            $application = $result->fetch_assoc();
        } else {
            $message = "Error updating application: " . $conn->error;
        }
    }
    
    // Handle Notification
    if (isset($_POST['notify_student'])) {
        $student_email = $_POST['student_email'];
        $student_phone = $_POST['student_phone'];
        
        // Fetch current status
        $status_query = $conn->query("SELECT status FROM applications WHERE id=$app_id");
        if($status_query->num_rows > 0) {
            $curr_app = $status_query->fetch_assoc();
            $status_msg = $curr_app['status'];
            
            // Simulate Sending Email/SMS
            $message = "Notification Sent Successfully!<br>";
            $message .= "<strong>Email to $student_email:</strong> 'Dear Student, your application status has been updated to $status_msg.'<br>";
            $message .= "<strong>SMS to $student_phone:</strong> 'Admission Portal: Application Status: $status_msg'";
        }
    }

    if (isset($_POST['status'])) {
        $status = $_POST['status'];
        // Validate status enum
        $allowed_status = ['Submitted', 'Under Review', 'Accepted', 'Rejected'];
        if (in_array($status, $allowed_status)) {
            $sql = "UPDATE applications SET status='$status' WHERE id=$app_id";
            if ($conn->query($sql) === TRUE) {
                $message = "Application status updated to <strong>$status</strong> successfully!";
            } else {
                $message = "Error updating status: " . $conn->error;
            }
        }
    }
    
    // Handle Payment Status Update
    if (isset($_POST['payment_status'])) {
        $p_status = $_POST['payment_status'];
        $allowed_p_status = ['Pending', 'Paid', 'Verification Pending'];
        if (in_array($p_status, $allowed_p_status)) {
            $sql = "UPDATE applications SET payment_status='$p_status' WHERE id=$app_id";
            if ($conn->query($sql) === TRUE) {
                $message = "Payment status updated to <strong>$p_status</strong> successfully!";
            } else {
                $message = "Error updating payment status: " . $conn->error;
            }
        }
    }
}

// Fetch Application Details
$sql = "SELECT a.*, p.program_name, p.degree_level, u.full_name as student_name, u.email, u.phone, u.cnic 
        FROM applications a 
        JOIN programs p ON a.program_id = p.id 
        JOIN users u ON a.user_id = u.id 
        WHERE a.id = $app_id";
$result = $conn->query($sql);

if ($result->num_rows == 0) {
    echo "<div class='container' style='padding: 50px;'><div class='alert alert-danger'>Application not found.</div></div>";
    include 'includes/footer.php';
    exit();
}

$application = $result->fetch_assoc();
$user_id = $application['user_id'];

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

// 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);
?>

<div class="dashboard-container">
    <div class="sidebar admin-sidebar">
        <?php include 'includes/sidebar.php'; ?>
    </div>

    <div class="main-content">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Review Application #<?php echo $application['id']; ?></h3>
                <a href="index.php" class="btn-outline" style="padding: 5px 15px; text-decoration: none;">Back to List</a>
            </div>

            <?php if($message): ?>
                <div class="alert alert-success"><?php echo $message; ?></div>
            <?php endif; ?>

            <div style="background: #e8f5e9; padding: 20px; border: 1px solid #a5d6a7; margin-bottom: 20px; border-radius: 4px;">
                <h4 style="margin-top: 0; color: #2e7d32;">Edit Application Details</h4>
                <form method="POST" action="">
                    <input type="hidden" name="edit_application" value="1">
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                        <div class="form-group">
                            <label>Full Name</label>
                            <input type="text" name="full_name" class="form-control" value="<?php echo $application['student_name']; ?>" required>
                        </div>
                        <div class="form-group">
                            <label>ID Card Number (CNIC)</label>
                            <input type="text" name="cnic" class="form-control" value="<?php echo $application['cnic']; ?>" required>
                        </div>
                        <div class="form-group">
                            <label>Mobile Number</label>
                            <input type="text" name="phone" class="form-control" value="<?php echo $application['phone']; ?>" required>
                        </div>
                        <div class="form-group">
                            <label>Session</label>
                            <select name="session" class="form-control" required>
                                <option value="Fall" <?php if($application['session'] == 'Fall') echo 'selected'; ?>>Fall</option>
                                <option value="Spring" <?php if($application['session'] == 'Spring') echo 'selected'; ?>>Spring</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Academic Year</label>
                            <select name="academic_year" class="form-control" required>
                                <?php 
                                $cur_year = date('Y');
                                for($i=$cur_year; $i<=$cur_year+2; $i++) {
                                    $selected = ($application['academic_year'] == $i) ? 'selected' : '';
                                    echo "<option value='$i' $selected>$i</option>";
                                }
                                ?>
                            </select>
                        </div>
                    </div>
                    <button type="submit" class="btn-primary" style="padding: 8px 20px; background-color: #388e3c;"><i class="fas fa-save"></i> Update Application</button>
                </form>
            </div>

            <div style="background: #f1f8e9; padding: 20px; border: 1px solid #c5e1a5; margin-bottom: 20px; border-radius: 4px;">
                <h4 style="margin-top: 0;">Update Application Status</h4>
                <form method="POST" action="" style="display: flex; gap: 10px; align-items: center;">
                    <label>Current Status:</label>
                    <select name="status" class="form-control" style="width: auto; display: inline-block;">
                        <option value="Submitted" <?php if($application['status'] == 'Submitted') echo 'selected'; ?>>Submitted</option>
                        <option value="Under Review" <?php if($application['status'] == 'Under Review') echo 'selected'; ?>>Under Review</option>
                        <option value="Accepted" <?php if($application['status'] == 'Accepted') echo 'selected'; ?>>Accepted</option>
                        <option value="Rejected" <?php if($application['status'] == 'Rejected') echo 'selected'; ?>>Rejected</option>
                    </select>
                    <button type="submit" class="btn-primary" style="padding: 8px 20px;">Update Status</button>
                </form>
                
                <form method="POST" action="" style="margin-top: 15px; padding-top: 15px; border-top: 1px dashed #c5e1a5;">
                    <input type="hidden" name="notify_student" value="1">
                    <input type="hidden" name="student_email" value="<?php echo $application['email']; ?>">
                    <input type="hidden" name="student_phone" value="<?php echo $application['phone']; ?>">
                    <div style="display: flex; align-items: center; gap: 15px;">
                        <span><strong>Notify Student:</strong> Send status update via Email & SMS</span>
                        <button type="submit" class="btn-outline" style="padding: 5px 15px; background: #fff;">
                            <i class="fas fa-paper-plane"></i> Send Notification
                        </button>
                    </div>
                </form>
            </div>

            <div style="background: #e3f2fd; padding: 20px; border: 1px solid #90caf9; margin-bottom: 20px; border-radius: 4px;">
                <h4 style="margin-top: 0; color: #0d47a1;">Payment Information</h4>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                    <p><strong>Status:</strong> 
                        <?php 
                            $pay_color = 'red';
                            if($application['payment_status'] == 'Paid') $pay_color = 'green';
                            if($application['payment_status'] == 'Verification Pending') $pay_color = 'orange';
                        ?>
                        <span style="color: <?php echo $pay_color; ?>; font-weight: bold;"><?php echo $application['payment_status']; ?></span>
                    </p>
                    <p><strong>Method:</strong> <?php echo $application['payment_method'] ?? 'Bank Deposit'; ?></p>
                    <p><strong>Transaction ID:</strong> <?php echo $application['transaction_id'] ?? 'N/A'; ?></p>
                    <p><strong>Date:</strong> <?php echo $application['payment_date'] ? date('d M, Y h:i A', strtotime($application['payment_date'])) : 'N/A'; ?></p>
                    <?php if(!empty($application['payment_receipt'])): ?>
                        <p style="grid-column: span 2;">
                            <strong>Payment Receipt:</strong> 
                            <a href="../<?php echo $application['payment_receipt']; ?>" target="_blank" class="btn-outline" style="padding: 2px 10px; font-size: 0.8rem; margin-left: 10px;">
                                <i class="fas fa-file-invoice"></i> View Receipt
                            </a>
                        </p>
                    <?php endif; ?>
                </div>
                
                <form method="POST" action="" style="border-top: 1px solid #bbdefb; padding-top: 15px; display: flex; gap: 10px; align-items: center;">
                    <label>Update Payment Status:</label>
                    <select name="payment_status" class="form-control" style="width: auto; display: inline-block;">
                        <option value="Pending" <?php if($application['payment_status'] == 'Pending') echo 'selected'; ?>>Pending</option>
                        <option value="Verification Pending" <?php if($application['payment_status'] == 'Verification Pending') echo 'selected'; ?>>Verification Pending</option>
                        <option value="Paid" <?php if($application['payment_status'] == 'Paid') echo 'selected'; ?>>Paid (Verified)</option>
                    </select>
                    <button type="submit" class="btn-primary" style="padding: 8px 20px; background-color: #0277bd;">Update Payment</button>
                </form>
            </div>

            <div style="margin-bottom: 30px;">
                <h3 style="color: #263238; border-bottom: 2px solid #eee; padding-bottom: 10px;">Applicant Information</h3>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                    <p><strong>Name:</strong> <?php echo $application['student_name']; ?></p>
                    <p><strong>Email:</strong> <?php echo $application['email']; ?></p>
                    <p><strong>Phone:</strong> <?php echo $application['phone']; ?></p>
                    <p><strong>CNIC:</strong> <?php echo $application['cnic']; ?></p>
                    <p><strong>Program Applied:</strong> <?php echo $application['program_name']; ?> (<?php echo $application['degree_level']; ?>)</p>
                    <p><strong>Submission Date:</strong> <?php echo date('d M, Y', strtotime($application['submission_date'])); ?></p>
                </div>
            </div>

            <?php if($personal): ?>
            <div style="margin-bottom: 30px;">
                <h3 style="color: #263238; border-bottom: 2px solid #eee; padding-bottom: 10px;">Personal Details</h3>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                    <p><strong>Father's Name:</strong> <?php echo $personal['father_name']; ?></p>
                    <p><strong>Date of Birth:</strong> <?php echo $personal['dob']; ?></p>
                    <p><strong>Gender:</strong> <?php echo $personal['gender']; ?></p>
                    <p><strong>City:</strong> <?php echo $personal['city']; ?></p>
                    <p><strong>Country:</strong> <?php echo $personal['country']; ?></p>
                    <p><strong>Address:</strong> <?php echo $personal['address']; ?></p>
                </div>
            </div>
            <?php endif; ?>

            <div style="margin-bottom: 30px;">
                <h3 style="color: #263238; border-bottom: 2px solid #eee; padding-bottom: 10px;">Academic Records</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: #263238; border-bottom: 2px solid #eee; padding-bottom: 10px;">Uploaded Documents</h3>
                <ul>
                    <?php while($row = $res_docs->fetch_assoc()): ?>
                        <li>
                            <?php echo $row['document_type']; ?> 
                            <a href="../<?php echo $row['file_path']; ?>" target="_blank" style="margin-left: 10px; font-size: 0.9rem; color: #00bcd4;"><i class="fas fa-external-link-alt"></i> View File</a>
                        </li>
                    <?php endwhile; ?>
                </ul>
            </div>
        </div>
    </div>
</div>

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