
<?php
// Handle view application
if (isset($_GET['action']) && $_GET['action'] === 'view' && isset($_GET['id'])) {
    $studentId = $_GET['id'];
    
    // Get student information
    $stmt = $pdo->prepare("SELECT * FROM students WHERE id = ?");
    $stmt->execute([$studentId]);
    $student = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Get education history
    $stmt = $pdo->prepare("SELECT * FROM education_history WHERE student_id = ?");
    $stmt->execute([$studentId]);
    $educationHistory = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get examination results
    $stmt = $pdo->prepare("SELECT * FROM examination_results WHERE student_id = ?");
    $stmt->execute([$studentId]);
    $examResults = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get referee information
    $stmt = $pdo->prepare("SELECT * FROM referees WHERE student_id = ?");
    $stmt->execute([$studentId]);
    $referee = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Get admin decision
    $stmt = $pdo->prepare("SELECT * FROM admin_decisions WHERE student_id = ?");
    $stmt->execute([$studentId]);
    $adminDecision = $stmt->fetch(PDO::FETCH_ASSOC);
    
    ?>
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h4 class="mb-0">Application Details - <?php echo $student['registration_no']; ?></h4>
                    <a href="?page=admin_applications" class="btn btn-secondary">Back to Applications</a>
                </div>
                <div class="card-body">
                    <!-- Personal Information -->
                    <div class="form-section">
                        <h3>Personal Information</h3>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Registration Number</label>
                                <input type="text" class="form-control" value="<?php echo $student['registration_no']; ?>" readonly>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Application Status</label>
                                <select class="form-select" id="application_status" name="application_status">
                                    <option value="Pending" <?php echo $student['application_status'] === 'Pending' ? 'selected' : ''; ?>>Pending</option>
                                    <option value="Under Review" <?php echo $student['application_status'] === 'Under Review' ? 'selected' : ''; ?>>Under Review</option>
                                    <option value="Approved" <?php echo $student['application_status'] === 'Approved' ? 'selected' : ''; ?>>Approved</option>
                                    <option value="Rejected" <?php echo $student['application_status'] === 'Rejected' ? 'selected' : ''; ?>>Rejected</option>
                                </select>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Surname</label>
                                <input type="text" class="form-control" value="<?php echo $student['surname']; ?>" readonly>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">First Name</label>
                                <input type="text" class="form-control" value="<?php echo $student['first_name']; ?>" readonly>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Other Name</label>
                                <input type="text" class="form-control" value="<?php echo $student['other_name']; ?>" readonly>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Sex</label>
                                <input type="text" class="form-control" value="<?php echo $student['sex']; ?>" readonly>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Date of Birth</label>
                                <input type="text" class="form-control" value="<?php echo date('d M Y', strtotime($student['date_of_birth'])); ?>" readonly>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Nationality</label>
                                <input type="text" class="form-control" value="<?php echo $student['nationality']; ?>" readonly>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">State of Origin</label>
                                <input type="text" class="form-control" value="<?php echo $student['state_of_origin']; ?>" readonly>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Local Government Area</label>
                                <input type="text" class="form-control" value="<?php echo $student['lga']; ?>" readonly>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Mobile Phone</label>
                                <input type="text" class="form-control" value="<?php echo $student['mobile_phone']; ?>" readonly>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Residential Phone</label>
                                <input type="text" class="form-control" value="<?php echo $student['residential_phone']; ?>" readonly>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Email</label>
                                <input type="text" class="form-control" value="<?php echo $student['email']; ?>" readonly>
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Permanent Address</label>
                                <textarea class="form-control" rows="3" readonly><?php echo $student['permanent_address']; ?></textarea>
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Extra Curricular Activities</label>
                                <textarea class="form-control" rows="2" readonly><?php echo $student['extra_curricular']; ?></textarea>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Next of Kin & Sponsor -->
                    <div class="form-section">
                        <h3>Next of Kin & Sponsor</h3>
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Next of Kin/Parent Name & Address</label>
                                <textarea class="form-control" rows="3" readonly><?php echo $student['nok_name']; ?></textarea>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Next of Kin Telephone</label>
                                <input type="text" class="form-control" value="<?php echo $student['nok_phone']; ?>" readonly>
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Sponsor's Name & Address</label>
                                <textarea class="form-control" rows="3" readonly><?php echo $student['sponsor_name']; ?></textarea>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Sponsor's Telephone</label>
                                <input type="text" class="form-control" value="<?php echo $student['sponsor_phone']; ?>" readonly>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Sponsor's Occupation</label>
                                <input type="text" class="form-control" value="<?php echo $student['sponsor_occupation']; ?>" readonly>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Choice of Course -->
                    <div class="form-section">
                        <h3>Choice of Course/Subject (O' Level)</h3>
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Subject 1</label>
                                <input type="text" class="form-control" value="<?php echo $student['subject1']; ?>" readonly>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Subject 2</label>
                                <input type="text" class="form-control" value="<?php echo $student['subject2']; ?>" readonly>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Subject 3</label>
                                <input type="text" class="form-control" value="<?php echo $student['subject3']; ?>" readonly>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Education History -->
                    <div class="form-section">
                        <h3>Post-Primary Institution Attended with Dates</h3>
                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th>Name of Institution</th>
                                        <th>From (Date)</th>
                                        <th>To (Date)</th>
                                        <th>Qualifications Obtained</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($educationHistory as $edu): ?>
                                    <tr>
                                        <td><?php echo $edu['institution_name']; ?></td>
                                        <td><?php echo date('M Y', strtotime($edu['from_date'])); ?></td>
                                        <td><?php echo date('M Y', strtotime($edu['to_date'])); ?></td>
                                        <td><?php echo $edu['qualification']; ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    
                    <!-- Examination Results -->
                    <div class="form-section">
                        <h3>School Certificate Results</h3>
                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th>Names of Examination</th>
                                        <th>Date</th>
                                        <th>Exam Number</th>
                                        <th>Subjects & Grades</th>
                                        <th>Credentials Enclosed?</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($examResults as $exam): ?>
                                    <tr>
                                        <td><?php echo $exam['exam_type']; ?></td>
                                        <td><?php echo date('M Y', strtotime($exam['exam_date'])); ?></td>
                                        <td><?php echo $exam['exam_number']; ?></td>
                                        <td><?php echo $exam['subjects_grades']; ?></td>
                                        <td><?php echo $exam['credentials_attached'] ? 'Yes' : 'No'; ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    
                    <!-- Referee Information -->
                    <div class="form-section">
                        <h3>Referee Information</h3>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Referee Full Name</label>
                                <input type="text" class="form-control" value="<?php echo $referee['full_name']; ?>" readonly>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Occupation</label>
                                <input type="text" class="form-control" value="<?php echo $referee['occupation']; ?>" readonly>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Post Held</label>
                                <input type="text" class="form-control" value="<?php echo $referee['post_held']; ?>" readonly>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Date</label>
                                <input type="text" class="form-control" value="<?php echo date('d M Y', strtotime($referee['date'])); ?>" readonly>
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Address</label>
                                <textarea class="form-control" rows="3" readonly><?php echo $referee['address']; ?></textarea>
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Referee's Signature</label>
                                <?php if ($referee['signature_data']): ?>
                                    <img src="<?php echo $referee['signature_data']; ?>" alt="Referee Signature" style="max-height: 150px;">
                                <?php else: ?>
                                    <p>No signature provided</p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Applicant Signature -->
                    <div class="form-section">
                        <h3>Applicant Signature</h3>
                        <?php if ($student['signature_data']): ?>
                            <img src="<?php echo $student['signature_data']; ?>" alt="Applicant Signature" style="max-height: 150px;">
                        <?php else: ?>
                            <p>No signature provided</p>
                        <?php endif; ?>
                    </div>
                    
                    <!-- Admin Decision -->
                    <div class="form-section">
                        <h3>Administrative Decision</h3>
                        <form method="post" action="">
                            <input type="hidden" name="action" value="admin_decision">
                            <input type="hidden" name="student_id" value="<?php echo $studentId; ?>">
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="qualified" id="qualified" <?php echo $adminDecision && $adminDecision['qualified'] ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="qualified">
                                            Qualified
                                        </label>
                                    </div>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="officer_name" class="form-label">Name & Signature of Officer</label>
                                    <input type="text" class="form-control" id="officer_name" name="officer_name" value="<?php echo $adminDecision['officer_name'] ?? ''; ?>" required>
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label class="form-label">Officer Signature</label>
                                    <div class="signature-wrapper border p-2 bg-light">
                                        <canvas id="officer_signature" class="signature-canvas"></canvas>
                                        <div class="d-flex justify-content-between mt-2">
                                            <span>Clear</span>
                                            <button type="button" class="btn btn-secondary btn-sm" id="officer_signature_clear">Clear Pad</button>
                                        </div>
                                        <input type="hidden" id="officer_signature_data" name="officer_signature" value="<?php echo $adminDecision['officer_signature'] ?? ''; ?>">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="d-flex justify-content-between">
                                <button type="submit" class="btn btn-primary">Save Decision</button>
                                <button type="button" class="btn btn-success" onclick="updateApplicationStatus(<?php echo $studentId; ?>)">Update Status</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
    document.addEventListener("DOMContentLoaded", function() {
        // Save signature data before form submission
        const form = document.querySelector("form");
        form.addEventListener("submit", function() {
            const canvas = document.getElementById("officer_signature");
            const data = canvas.toDataURL();
            document.getElementById("officer_signature_data").value = data;
        });
        
        // Update application status
        window.updateApplicationStatus = function(studentId) {
            const status = document.getElementById("application_status").value;
            
            if (confirm("Are you sure you want to update the application status to " + status + "?")) {
                const form = document.createElement("form");
                form.method = "POST";
                form.innerHTML = `
                    <input type="hidden" name="action" value="update_status">
                    <input type="hidden" name="student_id" value="${studentId}">
                    <input type="hidden" name="status" value="${status}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        };
    });
    </script>
    <?php
} else {
    // List all applications
    ?>
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    Manage Applications
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <div class="row">
                            <div class="col-md-4">
                                <input type="text" class="form-control" id="search" placeholder="Search by name, email, or registration number...">
                            </div>
                            <div class="col-md-2">
                                <select class="form-select" id="status_filter">
                                    <option value="">All Status</option>
                                    <option value="Pending">Pending</option>
                                    <option value="Under Review">Under Review</option>
                                    <option value="Approved">Approved</option>
                                    <option value="Rejected">Rejected</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <select class="form-select" id="payment_filter">
                                    <option value="">All Payment</option>
                                    <option value="Pending">Pending</option>
                                    <option value="Paid">Paid</option>
                                    <option value="Failed">Failed</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <button class="btn btn-primary w-100" id="filter_btn">Filter</button>
                            </div>
                            <div class="col-md-2">
                                <button class="btn btn-secondary w-100" id="reset_btn">Reset</button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>Reg. No.</th>
                                    <th>Name</th>
                                    <th>Email</th>
                                    <th>Phone</th>
                                    <th>Payment</th>
                                    <th>Status</th>
                                    <th>Date</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="applications_table">
                                <?php
                                $stmt = $pdo->query("SELECT * FROM students ORDER BY created_at DESC");
                                while ($student = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                    echo "<tr>";
                                    echo "<td>" . $student['registration_no'] . "</td>";
                                    echo "<td>" . $student['first_name'] . " " . $student['surname'] . "</td>";
                                    echo "<td>" . $student['email'] . "</td>";
                                    echo "<td>" . $student['mobile_phone'] . "</td>";
                                    echo "<td>" . $student['payment_status'] . "</td>";
                                    echo "<td><span class=\"status-badge status-" . strtolower(str_replace(' ', '-', $student['application_status'])) . "\">" . $student['application_status'] . "</span></td>";
                                    echo "<td>" . date('d M Y', strtotime($student['created_at'])) . "</td>";
                                    echo "<td>
                                            <a href=\"?page=admin_applications&action=view&id=" . $student['id'] . "\" class=\"btn btn-sm btn-primary\">View</a>
                                            <button class=\"btn btn-sm btn-danger\" onclick=\"deleteApplication(" . $student['id'] . ")\">Delete</button>
                                          </td>";
                                    echo "</tr>";
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
    document.addEventListener("DOMContentLoaded", function() {
        // Filter applications
        document.getElementById("filter_btn").addEventListener("click", function() {
            const search = document.getElementById("search").value;
            const status = document.getElementById("status_filter").value;
            const payment = document.getElementById("payment_filter").value;
            
            const xhr = new XMLHttpRequest();
            xhr.open("POST", "", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    document.getElementById("applications_table").innerHTML = xhr.responseText;
                }
            };
            xhr.send("action=filter_applications&search=" + encodeURIComponent(search) + "&status=" + encodeURIComponent(status) + "&payment=" + encodeURIComponent(payment));
        });
        
        // Reset filters
        document.getElementById("reset_btn").addEventListener("click", function() {
            document.getElementById("search").value = "";
            document.getElementById("status_filter").value = "";
            document.getElementById("payment_filter").value = "";
            document.getElementById("filter_btn").click();
        });
        
        // Delete application
        window.deleteApplication = function(id) {
            if (confirm("Are you sure you want to delete this application?")) {
                const xhr = new XMLHttpRequest();
                xhr.open("POST", "", true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        location.reload();
                    }
                };
                xhr.send("action=delete_application&id=" + id);
            }
        };
    });
    </script>
    <?php
}

// Handle AJAX requests for filtering and deleting
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'filter_applications') {
        $search = $_POST['search'] ?? '';
        $status = $_POST['status'] ?? '';
        $payment = $_POST['payment'] ?? '';
        
        $query = "SELECT * FROM students WHERE 1=1";
        $params = [];
        
        if (!empty($search)) {
            $query .= " AND (first_name LIKE ? OR surname LIKE ? OR email LIKE ? OR registration_no LIKE ?)";
            $searchParam = "%$search%";
            $params = array_merge($params, [$searchParam, $searchParam, $searchParam, $searchParam]);
        }
        
        if (!empty($status)) {
            $query .= " AND application_status = ?";
            $params[] = $status;
        }
        
        if (!empty($payment)) {
            $query .= " AND payment_status = ?";
            $params[] = $payment;
        }
        
        $query .= " ORDER BY created_at DESC";
        
        $stmt = $pdo->prepare($query);
        $stmt->execute($params);
        
        while ($student = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo "<tr>";
            echo "<td>" . $student['registration_no'] . "</td>";
            echo "<td>" . $student['first_name'] . " " . $student['surname'] . "</td>";
            echo "<td>" . $student['email'] . "</td>";
            echo "<td>" . $student['mobile_phone'] . "</td>";
            echo "<td>" . $student['payment_status'] . "</td>";
            echo "<td><span class=\"status-badge status-" . strtolower(str_replace(' ', '-', $student['application_status'])) . "\">" . $student['application_status'] . "</span></td>";
            echo "<td>" . date('d M Y', strtotime($student['created_at'])) . "</td>";
            echo "<td>
                    <a href=\"?page=admin_applications&action=view&id=" . $student['id'] . "\" class=\"btn btn-sm btn-primary\">View</a>
                    <button class=\"btn btn-sm btn-danger\" onclick=\"deleteApplication(" . $student['id'] . ")\">Delete</button>
                  </td>";
            echo "</tr>";
        }
        
        exit;
    } elseif ($_POST['action'] === 'delete_application') {
        $id = $_POST['id'] ?? 0;
        
        if ($id > 0) {
            // Delete related records
            $stmt = $pdo->prepare("DELETE FROM education_history WHERE student_id = ?");
            $stmt->execute([$id]);
            
            $stmt = $pdo->prepare("DELETE FROM examination_results WHERE student_id = ?");
            $stmt->execute([$id]);
            
            $stmt = $pdo->prepare("DELETE FROM referees WHERE student_id = ?");
            $stmt->execute([$id]);
            
            $stmt = $pdo->prepare("DELETE FROM admin_decisions WHERE student_id = ?");
            $stmt->execute([$id]);
            
            // Delete student
            $stmt = $pdo->prepare("DELETE FROM students WHERE id = ?");
            $stmt->execute([$id]);
        }
        
        exit;
    }
}
?>
