<?php
session_start();
require_once 'config.php';

// Enable error reporting for development
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Debugging: Log session data
error_log("Document verification accessed. Session data: " . print_r($_SESSION, true));

if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'counselor') {
    header('Location: counselor-login.php');
    exit;
}

// Handle document approval/rejection
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');

    try {
        if (!isset($pdo) || !$pdo) {
            throw new Exception('Database connection not established');
        }

        // Validate request
        if (!isset($_POST['action'], $_POST['doc_id']) || 
            !in_array($_POST['action'], ['approve', 'reject'])) {
            throw new Exception('Missing or invalid parameters');
        }

        $doc_id = (int)$_POST['doc_id'];
        $student_id = isset($_POST['student_id']) ? (int)$_POST['student_id'] : null;
        $review_notes = isset($_POST['review_notes']) ? trim($_POST['review_notes']) : '';

        // Start transaction
        $pdo->beginTransaction();

        // Update document status
        $status = ($_POST['action'] === 'approve') ? 'approved' : 'rejected';
        $stmt = $pdo->prepare("UPDATE student_documents 
                              SET status = ?, review_notes = ?, reviewed_by = ?, reviewed_at = NOW() 
                              WHERE id = ?");
        $stmt->execute([$status, $review_notes, $_SESSION['user_id'], $doc_id]);

        if ($stmt->rowCount() === 0) {
            throw new Exception('Document not found or already processed');
        }

        // Create notification for student
        if ($student_id > 0) {
            $action = ($_POST['action'] === 'approve') ? 'approved' : 'rejected';
            $message = "Your document has been $action by your counselor";

            if (!empty($review_notes)) {
                $message .= " with notes: " . htmlspecialchars($review_notes, ENT_QUOTES, 'UTF-8');
            }

            $notification_stmt = $pdo->prepare("INSERT INTO notifications (
                user_id, title, message, is_read, notification_type, related_id, related_type, created_at
            ) VALUES (?, ?, ?, 0, 'document', ?, 'student_document', NOW())");

            $notification_stmt->execute([
                $student_id,
                "Document $action",
                $message,
                $doc_id
            ]);
        }

        // Commit transaction
        $pdo->commit();

        echo json_encode(['success' => true]);
        exit;
    } catch (Exception $e) {
        if (isset($pdo) && $pdo) {
            $pdo->rollBack();
        }
        error_log("Document update failed: " . $e->getMessage());
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        exit;
    }
}

// Get documents that need review
try {
    $stmt = $pdo->prepare("SELECT sd.*, s.first_name, s.last_name, s.id as student_id
                          FROM student_documents sd
                          JOIN students s ON sd.student_id = s.id
                          WHERE s.assigned_counselor_id = ? AND sd.status IN ('pending', 'uploaded')
                          ORDER BY sd.created_at DESC");
    $stmt->execute([$_SESSION['user_id']]);
    $documents = $stmt->fetchAll();

    error_log("Found " . count($documents) . " documents for counselor ID: " . $_SESSION['user_id']);
} catch (Exception $e) {
    error_log("Error fetching documents: " . $e->getMessage());
    $documents = [];
}

// Get counselor data
try {
    $stmt = $pdo->prepare("SELECT first_name, last_name FROM counselors WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $counselor = $stmt->fetch();
} catch (Exception $e) {
    error_log("Error fetching counselor data: " . $e->getMessage());
    $counselor = ['first_name' => '', 'last_name' => ''];
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Document Verification - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <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="css/style.css" rel="stylesheet">
    <style>
        .status-badge {
            font-size: 0.8em;
            padding: 5px 10px;
            border-radius: 20px;
            display: inline-block;
            min-width: 80px;
            text-align: center;
        }
        .status-pending, .status-uploaded {
            background: #fff3cd;
            color: #856404;
        }
        .status-approved {
            background: #d4edda;
            color: #155724;
        }
        .status-rejected {
            background: #f8d7da;
            color: #721c24;
        }
        .modal-dialog {
            max-width: 500px;
        }
        .empty-state {
            text-align: center;
            padding: 40px;
            color: #666;
            background: #f8f9fa;
            border-radius: 8px;
            margin-top: 20px;
        }
        .empty-state i {
            font-size: 60px;
            color: #ddd;
            margin-bottom: 20px;
        }
        .document-actions .btn {
            margin: 2px;
        }
        .document-row:hover {
            background-color: #f8f9fa;
        }
    </style>
</head>
<body>

<?php include 'counselor-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">Document Verification</h6>
        <h1 class="display-5">Documents to Verify</h1>
        <p class="mb-4">Welcome, <?= htmlspecialchars($counselor['first_name'] . ' ' . $counselor['last_name']) ?></p>
    </div>

    <?php if (empty($documents)): ?>
        <div class="empty-state">
            <i class="fas fa-file-alt"></i>
            <h3>No documents to review</h3>
            <p>There are currently no documents pending your review.</p>
            <p>When students upload documents, they will appear here.</p>
        </div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-hover">
                <thead class="thead-light">
                    <tr>
                        <th>Student</th>
                        <th>Document</th>
                        <th>Uploaded</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($documents as $doc): ?>
                    <tr class="document-row">
                        <td><?= htmlspecialchars($doc['first_name'] . ' ' . $doc['last_name']) ?></td>
                        <td><?= ucfirst(str_replace('_', ' ', $doc['document_type'])) ?></td>
                        <td><?= date('M j, Y g:i a', strtotime($doc['created_at'])) ?></td>
                        <td>
                            <span class="status-badge status-<?= htmlspecialchars($doc['status']) ?>">
                                <?= ucfirst($doc['status']) ?>
                            </span>
                        </td>
                        <td class="document-actions">
                            <div class="btn-group" role="group">
                                <a href="<?= htmlspecialchars($doc['file_path']) ?>" class="btn btn-sm btn-primary" target="_blank">
                                    <i class="fas fa-eye"></i> View
                                </a>
                                <button class="btn btn-sm btn-success approve-doc" 
                                        data-id="<?= $doc['id'] ?>" 
                                        data-student="<?= $doc['student_id'] ?>">
                                    <i class="fas fa-check"></i> Approve
                                </button>
                                <button class="btn btn-sm btn-danger reject-doc" 
                                        data-id="<?= $doc['id'] ?>" 
                                        data-student="<?= $doc['student_id'] ?>">
                                    <i class="fas fa-times"></i> Reject
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<!-- Rejection Reason Modal -->
<div class="modal fade" id="rejectModal" tabindex="-1" role="dialog" aria-labelledby="rejectModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="rejectModalLabel">Document Rejection</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="rejectForm">
                    <input type="hidden" name="doc_id" id="rejectDocId">
                    <input type="hidden" name="student_id" id="rejectStudentId">
                    <input type="hidden" name="action" value="reject">
                    <div class="form-group">
                        <label for="rejectReason">Reason for rejection:</label>
                        <textarea class="form-control" id="rejectReason" name="review_notes" rows="5" required
                                  placeholder="Please specify why this document is being rejected and what the student needs to correct"></textarea>
                        <small class="form-text text-muted">This feedback will be sent to the student</small>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="confirmReject">
                    <i class="fas fa-times"></i> Confirm Rejection
                </button>
            </div>
        </div>
    </div>
</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>
$(document).ready(function() {
    // Handle document approval
    $('.approve-doc').on('click', function() {
        const docId = $(this).data('id');
        const studentId = $(this).data('student');

        if (confirm('Are you sure you want to approve this document?\n\nThis action cannot be undone.')) {
            $.ajax({
                url: window.location.href,
                method: 'POST',
                dataType: 'json',
                data: {
                    action: 'approve',
                    doc_id: docId,
                    student_id: studentId,
                    review_notes: 'Document approved by counselor'
                },
                beforeSend: function() {
                    $('.approve-doc[data-id="' + docId + '"]').html('<i class="fas fa-spinner fa-spin"></i> Processing');
                },
                success: function(res) {
                    if (res.success) {
                        alert('Document approved successfully!');
                        location.reload();
                    } else {
                        alert('Error: ' + (res.error || 'Failed to approve document'));
                        $('.approve-doc[data-id="' + docId + '"]').html('<i class="fas fa-check"></i> Approve');
                    }
                },
                error: function(xhr) {
                    let errorMsg = 'Error: Failed to communicate with server';
                    try {
                        const res = JSON.parse(xhr.responseText);
                        if (res.error) errorMsg = res.error;
                    } catch (e) {}
                    alert(errorMsg);
                    $('.approve-doc[data-id="' + docId + '"]').html('<i class="fas fa-check"></i> Approve');
                }
            });
        }
    });

    // Handle document rejection
    $('.reject-doc').on('click', function() {
        const docId = $(this).data('id');
        const studentId = $(this).data('student');

        $('#rejectDocId').val(docId);
        $('#rejectStudentId').val(studentId);
        $('#rejectReason').val('');
        $('#rejectModal').modal('show');
    });

    // Confirm rejection
    $('#confirmReject').on('click', function() {
        const reason = $('#rejectReason').val().trim();
        if (reason === '') {
            alert('Please provide a reason for rejection');
            return;
        }

        $(this).html('<i class="fas fa-spinner fa-spin"></i> Processing');

        $.ajax({
            url: window.location.href,
            method: 'POST',
            dataType: 'json',
            data: $('#rejectForm').serialize(),
            success: function(res) {
                if (res.success) {
                    $('#rejectModal').modal('hide');
                    alert('Document rejected successfully!');
                    location.reload();
                } else {
                    alert('Error: ' + (res.error || 'Failed to reject document'));
                    $('#confirmReject').html('<i class="fas fa-times"></i> Confirm Rejection');
                }
            },
            error: function(xhr) {
                let errorMsg = 'Error: Failed to communicate with server';
                try {
                    const res = JSON.parse(xhr.responseText);
                    if (res.error) errorMsg = res.error;
                } catch (e) {}
                alert(errorMsg);
                $('#confirmReject').html('<i class="fas fa-times"></i> Confirm Rejection');
            }
        });
    });
});
</script>
</body>
</html>
