<?php
/**
 * Admin Document Verification Management
 * View and manage all student documents by verification status
 */

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.");
}

// Get filters
$status_filter = $_GET['status'] ?? 'pending';
$student_filter = $_GET['student'] ?? '';
$document_type_filter = $_GET['document_type'] ?? '';
$sort_order = $_GET['sort'] ?? 'newest';

// Get students for filter dropdown
$students = $pdo->query("SELECT s.id, s.first_name, s.last_name, u.email 
                        FROM students s 
                        JOIN users u ON s.id = u.id 
                        ORDER BY s.last_name, s.first_name")->fetchAll();

// Get document types for filter dropdown
$document_types = [
    'passport' => 'Passport Copy',
    'transcript' => 'Academic Transcript',
    'diploma' => 'Diploma/Certificate',
    'recommendation_letter' => 'Recommendation Letter',
    'sop' => 'Statement of Purpose',
    'cv' => 'Curriculum Vitae',
    'language_test' => 'Language Test Results',
    'financial_statement' => 'Financial Statement',
    'other' => 'Other Document'
];

// Build query for documents
$sql = "SELECT sd.*, 
               s.first_name as student_first, s.last_name as student_last,
               u.email as student_email,
               c.first_name as counselor_first, c.last_name as counselor_last,
               a.first_name as admin_first, a.last_name as admin_last,
               un.name as university_name, p.name as program_name
        FROM student_documents sd
        JOIN students s ON sd.student_id = s.id
        JOIN users u ON s.id = u.id
        LEFT JOIN counselors c ON s.assigned_counselor_id = c.id
        LEFT JOIN admins a ON sd.reviewed_by = a.id";

// Add application join to get program info
$sql .= " LEFT JOIN applications app ON s.id = app.student_id AND app.application_status IN ('submitted', 'under_review', 'accepted')
          LEFT JOIN programs p ON app.program_id = p.id
          LEFT JOIN universities un ON p.university_id = un.id";

// Add WHERE clause
$conditions = [];
$params = [];

// Add status filter
if ($status_filter === 'pending') {
    $conditions[] = "sd.status = 'pending'";
} elseif ($status_filter === 'uploaded') {
    $conditions[] = "sd.status = 'uploaded'";
} elseif ($status_filter === 'approved') {
    $conditions[] = "sd.status = 'approved'";
} elseif ($status_filter === 'rejected') {
    $conditions[] = "sd.status = 'rejected'";
}

// Add student filter
if ($student_filter) {
    $conditions[] = "sd.student_id = ?";
    $params[] = $student_filter;
}

// Add document type filter
if ($document_type_filter) {
    $conditions[] = "sd.document_type = ?";
    $params[] = $document_type_filter;
}

// Combine conditions
if ($conditions) {
    $sql .= " WHERE " . implode(" AND ", $conditions);
}

// Add ORDER BY clause
switch ($sort_order) {
    case 'oldest':
        $sql .= " ORDER BY sd.created_at ASC";
        break;
    case 'status':
        $sql .= " ORDER BY sd.status, sd.created_at DESC";
        break;
    default: // newest
        $sql .= " ORDER BY sd.created_at DESC";
        break;
}

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$documents = $stmt->fetchAll();

// Get document statistics
$stats = [
    'pending' => $pdo->query("SELECT COUNT(*) FROM student_documents WHERE status = 'pending'")->fetchColumn(),
    'uploaded' => $pdo->query("SELECT COUNT(*) FROM student_documents WHERE status = 'uploaded'")->fetchColumn(),
    'approved' => $pdo->query("SELECT COUNT(*) FROM student_documents WHERE status = 'approved'")->fetchColumn(),
    'rejected' => $pdo->query("SELECT COUNT(*) FROM student_documents WHERE status = 'rejected'")->fetchColumn(),
    'total' => $pdo->query("SELECT COUNT(*) FROM student_documents")->fetchColumn()
];

// Handle document verification
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['verify_document'])) {
        $doc_id = $_POST['doc_id'];
        $action = $_POST['action']; // approve or reject
        $notes = trim($_POST['notes'] ?? '');
        
        if ($action !== 'approve' && $action !== 'reject') {
            $error = "Invalid action specified.";
        } else {
            try {
                // Start transaction
                $pdo->beginTransaction();
                
                // Update document status
                $status = $action === 'approve' ? 'approved' : 'rejected';
                $stmt = $pdo->prepare("UPDATE student_documents SET status = ?, reviewed_by = ?, reviewed_at = NOW(), review_notes = ?, updated_at = NOW() WHERE id = ?");
                $stmt->execute([$status, $_SESSION['user_id'], $notes, $doc_id]);
                
                // Get document details for notification
                $doc_stmt = $pdo->prepare("SELECT sd.*, s.first_name, s.last_name, s.assigned_counselor_id
                                          FROM student_documents sd
                                          JOIN students s ON sd.student_id = s.id
                                          WHERE sd.id = ?");
                $doc_stmt->execute([$doc_id]);
                $doc = $doc_stmt->fetch();
                
                if ($doc) {
                    // Create notification for student
                    $pdo->prepare("INSERT INTO notifications (
                        user_id, title, message, is_read, notification_type, created_at
                    ) VALUES (?, ?, ?, 0, 'document', NOW())")->execute([
                        $doc['student_id'],
                        "Document " . ucfirst($status),
                        "Your document has been {$status}. " . ($notes ? $notes : '')
                    ]);
                    
                    // Create activity log
                    $pdo->prepare("INSERT INTO activities (
                        user_id, activity_type, description, created_at
                    ) VALUES (?, ?, ?, NOW())")->execute([
                        $_SESSION['user_id'],
                        "document_verified",
                        "Admin {$admin['first_name']} {$admin['last_name']} {$status} document #{$doc_id}"
                    ]);
                }
                
                // Commit transaction
                $pdo->commit();
                
                $success = "Document status updated successfully!";
                header("Location: admin-verified-documents.php?status={$status_filter}" . ($student_filter ? "&student={$student_filter}" : "") . ($document_type_filter ? "&document_type={$document_type_filter}" : "") . ($sort_order ? "&sort={$sort_order}" : ""));
                exit;
                
            } catch (Exception $e) {
                $pdo->rollback();
                $error = "Failed to update document status. Please try again.";
            }
        }
    }
}

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

<!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 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>
        .stat-card {
            border-left: 5px solid #3fb7fe;
            margin-bottom: 20px;
        }
        .stat-card .icon {
            font-size: 2em;
            opacity: 0.2;
        }
        .table thead th {
            background-color: #f8f9fa;
            border-top: 0;
        }
        .status-badge {
            font-size: 0.8em;
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 600;
        }
        .status-pending {
            background: #fff3cd;
            color: #856404;
        }
        .status-uploaded {
            background: #d1ecf1;
            color: #0c5460;
        }
        .status-approved {
            background: #d4edda;
            color: #155724;
        }
        .status-rejected {
            background: #f8d7da;
            color: #721c24;
        }
        .document-item {
            border-left: 3px solid #3fb7fe;
            padding-left: 15px;
            margin-bottom: 10px;
        }
        .filter-container {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 30px;
        }
        .action-buttons {
            display: flex;
            gap: 5px;
        }
        .modal-dialog {
            max-width: 600px;
        }
        .review-info {
            font-size: 0.9em;
            color: #666;
            margin-top: 5px;
        }
        .document-preview {
            max-width: 100%;
            max-height: 150px;
            object-fit: contain;
            border: 1px solid #ddd;
            border-radius: 5px;
            margin: 10px 0;
        }
    </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">Document Management</h6>
        <h1 class="display-5">Document Verification Center</h1>
    </div>

    <?php if (isset($error)): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    
    <?php if (isset($success)): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>

    <!-- Statistics -->
    <div class="row mb-4">
        <div class="col-md-3 mb-3">
            <div class="card stat-card">
                <div class="card-body">
                    <div class="float-right"><i class="fas fa-folder icon"></i></div>
                    <h6>Total Documents</h6>
                    <h3><?= $stats['total'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="card stat-card" style="border-left-color: #ffc107;">
                <div class="card-body">
                    <div class="float-right"><i class="fas fa-clock icon" style="color: #ffc107;"></i></div>
                    <h6>Pending Review</h6>
                    <h3><?= $stats['pending'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="card stat-card" style="border-left-color: #17a2b8;">
                <div class="card-body">
                    <div class="float-right"><i class="fas fa-upload icon" style="color: #17a2b8;"></i></div>
                    <h6>Uploaded</h6>
                    <h3><?= $stats['uploaded'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="card stat-card" style="border-left-color: #28a745;">
                <div class="card-body">
                    <div class="float-right"><i class="fas fa-check-circle icon" style="color: #28a745;"></i></div>
                    <h6>Approved</h6>
                    <h3><?= $stats['approved'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="card stat-card" style="border-left-color: #dc3545;">
                <div class="card-body">
                    <div class="float-right"><i class="fas fa-times-circle icon" style="color: #dc3545;"></i></div>
                    <h6>Rejected</h6>
                    <h3><?= $stats['rejected'] ?></h3>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="filter-container">
        <form method="GET">
            <div class="row">
                <div class="col-md-3 mb-2">
                    <label>Status</label>
                    <select name="status" class="form-control" onchange="this.form.submit()">
                        <option value="pending" <?= $status_filter === 'pending' ? 'selected' : '' ?>>Pending Review (<?= $stats['pending'] ?>)</option>
                        <option value="uploaded" <?= $status_filter === 'uploaded' ? 'selected' : '' ?>>Uploaded (<?= $stats['uploaded'] ?>)</option>
                        <option value="approved" <?= $status_filter === 'approved' ? 'selected' : '' ?>>Approved (<?= $stats['approved'] ?>)</option>
                        <option value="rejected" <?= $status_filter === 'rejected' ? 'selected' : '' ?>>Rejected (<?= $stats['rejected'] ?>)</option>
                    </select>
                </div>
                <div class="col-md-3 mb-2">
                    <label>Student</label>
                    <select name="student" class="form-control" onchange="this.form.submit()">
                        <option value="">All Students</option>
                        <?php foreach ($students as $s): ?>
                        <option value="<?= $s['id'] ?>" <?= $student_filter == $s['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($s['first_name'] . ' ' . $s['last_name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3 mb-2">
                    <label>Document Type</label>
                    <select name="document_type" class="form-control" onchange="this.form.submit()">
                        <option value="">All Document Types</option>
                        <?php foreach ($document_types as $value => $label): ?>
                        <option value="<?= $value ?>" <?= $document_type_filter == $value ? 'selected' : '' ?>>
                            <?= $label ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3 mb-2">
                    <label>Sort Order</label>
                    <select name="sort" class="form-control" onchange="this.form.submit()">
                        <option value="newest" <?= $sort_order === 'newest' ? 'selected' : '' ?>>Newest First</option>
                        <option value="oldest" <?= $sort_order === 'oldest' ? 'selected' : '' ?>>Oldest First</option>
                        <option value="status" <?= $sort_order === 'status' ? 'selected' : '' ?>>By Status</option>
                    </select>
                </div>
            </div>
        </form>
    </div>

    <!-- Documents Table -->
    <div class="table-responsive">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>Student</th>
                    <th>Document</th>
                    <th>Status</th>
                    <th>Uploaded</th>
                    <th>Reviewed By</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($documents)): ?>
                <tr>
                    <td colspan="6" class="text-center">No documents found for the selected criteria.</td>
                </tr>
                <?php else: ?>
                <?php foreach ($documents as $doc): ?>
                <tr>
                    <td>
                        <strong><?= htmlspecialchars($doc['student_first'] . ' ' . $doc['student_last']) ?></strong><br>
                        <small><?= htmlspecialchars($doc['student_email']) ?></small>
                        <?php if ($doc['counselor_first']): ?>
                        <br><small class="text-muted">Counselor: <?= htmlspecialchars($doc['counselor_first'] . ' ' . $doc['counselor_last']) ?></small>
                        <?php endif; ?>
                    </td>
                    <td>
                        <strong><?= $document_types[$doc['document_type']] ?></strong><br>
                        <small><?= htmlspecialchars($doc['notes'] ?: 'No notes') ?></small>
                        <?php if ($doc['program_name']): ?>
                        <div class="mt-1">
                            <small class="text-muted">
                                For: <?= htmlspecialchars($doc['program_name']) ?><br>
                                <?= htmlspecialchars($doc['university_name']) ?>
                            </small>
                        </div>
                        <?php endif; ?>
                    </td>
                    <td>
                        <span class="status-badge status-<?= $doc['status'] ?>">
                            <?= ucfirst($doc['status']) ?>
                        </span>
                    </td>
                    <td>
                        <?= date('M j, Y H:i', strtotime($doc['created_at'])) ?>
                        <?php if ($doc['updated_at'] != $doc['created_at']): ?>
                        <br><small class="text-muted">Updated: <?= date('M j, Y H:i', strtotime($doc['updated_at'])) ?></small>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if ($doc['admin_first']): ?>
                        <?= htmlspecialchars($doc['admin_first'] . ' ' . $doc['admin_last']) ?>
                        <?php if ($doc['reviewed_at']): ?>
                        <br><small class="text-muted">On: <?= date('M j, Y', strtotime($doc['reviewed_at'])) ?></small>
                        <?php endif; ?>
                        <?php else: ?>
                        <small class="text-muted">Not reviewed</small>
                        <?php endif; ?>
                    </td>
                    <td>
                        <div class="action-buttons">
                            <a href="<?= htmlspecialchars($doc['file_path']) ?>" 
                               class="btn btn-sm btn-primary" target="_blank">
                                <i class="fas fa-eye"></i> View
                            </a>
                            <?php if ($doc['status'] === 'pending' || $doc['status'] === 'uploaded'): ?>
                            <button type="button" class="btn btn-sm btn-success" data-toggle="modal" data-target="#approveModal<?= $doc['id'] ?>">
                                <i class="fas fa-check"></i> Approve
                            </button>
                            <button type="button" class="btn btn-sm btn-danger" data-toggle="modal" data-target="#rejectModal<?= $doc['id'] ?>">
                                <i class="fas fa-times"></i> Reject
                            </button>
                            <?php elseif ($doc['review_notes']): ?>
                            <button type="button" class="btn btn-sm btn-info" data-toggle="modal" data-target="#notesModal<?= $doc['id'] ?>">
                                <i class="fas fa-sticky-note"></i> Notes
                            </button>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>

                <!-- Approve Modal -->
                <div class="modal fade" id="approveModal<?= $doc['id'] ?>" tabindex="-1" role="dialog">
                    <div class="modal-dialog" role="document">
                        <div class="modal-content">
                            <form method="POST">
                                <div class="modal-header">
                                    <h5 class="modal-title">Approve Document</h5>
                                    <button type="button" class="close" data-dismiss="modal">
                                        <span>&times;</span>
                                    </button>
                                </div>
                                <div class="modal-body">
                                    <input type="hidden" name="doc_id" value="<?= $doc['id'] ?>">
                                    <input type="hidden" name="action" value="approve">
                                    
                                    <div class="form-group">
                                        <label>Student</label>
                                        <p class="form-control-plaintext">
                                            <?= htmlspecialchars($doc['student_first'] . ' ' . $doc['student_last']) ?>
                                        </p>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label>Document Type</label>
                                        <p class="form-control-plaintext">
                                            <?= $document_types[$doc['document_type']] ?>
                                        </p>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label>Additional Notes (Optional)</label>
                                        <textarea name="notes" class="form-control" rows="3" 
                                                  placeholder="Add any comments for the student..."></textarea>
                                    </div>
                                    
                                    <div class="alert alert-info">
                                        <i class="fas fa-info-circle"></i> The student will be notified that their document has been approved.
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                                    <button type="submit" name="verify_document" class="btn btn-success">Approve Document</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <!-- Reject Modal -->
                <div class="modal fade" id="rejectModal<?= $doc['id'] ?>" tabindex="-1" role="dialog">
                    <div class="modal-dialog" role="document">
                        <div class="modal-content">
                            <form method="POST">
                                <div class="modal-header">
                                    <h5 class="modal-title">Reject Document</h5>
                                    <button type="button" class="close" data-dismiss="modal">
                                        <span>&times;</span>
                                    </button>
                                </div>
                                <div class="modal-body">
                                    <input type="hidden" name="doc_id" value="<?= $doc['id'] ?>">
                                    <input type="hidden" name="action" value="reject">
                                    
                                    <div class="form-group">
                                        <label>Student</label>
                                        <p class="form-control-plaintext">
                                            <?= htmlspecialchars($doc['student_first'] . ' ' . $doc['student_last']) ?>
                                        </p>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label>Document Type</label>
                                        <p class="form-control-plaintext">
                                            <?= $document_types[$doc['document_type']] ?>
                                        </p>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label>Reason for Rejection *</label>
                                        <textarea name="notes" class="form-control" rows="3" required
                                                  placeholder="Please specify why the document is being rejected..."></textarea>
                                    </div>
                                    
                                    <div class="alert alert-warning">
                                        <i class="fas fa-exclamation-triangle"></i> The student will be notified that their document has been rejected and will need to re-upload.
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                                    <button type="submit" name="verify_document" class="btn btn-danger">Reject Document</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                
                <!-- Notes Modal -->
                <div class="modal fade" id="notesModal<?= $doc['id'] ?>" tabindex="-1" role="dialog">
                    <div class="modal-dialog" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">Review Notes</h5>
                                <button type="button" class="close" data-dismiss="modal">
                                    <span>&times;</span>
                                </button>
                            </div>
                            <div class="modal-body">
                                <div class="form-group">
                                    <label>Reviewer</label>
                                    <p class="form-control-plaintext">
                                        <?= htmlspecialchars($doc['admin_first'] . ' ' . $doc['admin_last']) ?>
                                    </p>
                                </div>
                                
                                <div class="form-group">
                                    <label>Reviewed On</label>
                                    <p class="form-control-plaintext">
                                        <?= $doc['reviewed_at'] ? date('M j, Y H:i', strtotime($doc['reviewed_at'])) : 'Not specified' ?>
                                    </p>
                                </div>
                                
                                <div class="form-group">
                                    <label>Notes</label>
                                    <p class="form-control-plaintext" style="white-space: pre-wrap;">
                                        <?= htmlspecialchars($doc['review_notes'] ?: 'No notes provided') ?>
                                    </p>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </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>
    // Confirmation for document actions
    $('.btn-success, .btn-danger').on('click', function() {
        const action = $(this).find('i').hasClass('fa-check') ? 'approve' : 'reject';
        const docType = $(this).closest('tr').find('td:nth-child(2) strong').text();
        
        if (!confirm(`You are about to ${action} the ${docType} document. Continue?`)) {
            return false;
        }
    });
    
    // Auto-submit filters
    $('select').on('change', function() {
        $(this).closest('form').submit();
    });
</script>
</body>
</html>