<?php
/**
 * IBVTE Admin – Affiliation Applications
 * View/Edit/Approve/Reject applications submitted via apply.php
 */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

if (!checkDBConnection()) exit;
Auth()->requireRole(['super_admin', 'admin']);

$db    = DB();
$admin = Auth()->getUser();
$flash = getFlashMessage();
$action = $_GET['action'] ?? 'list';
$id     = intval($_GET['id'] ?? 0);

// ── APPROVE ──────────────────────────────────────────────────────────────────
if ($action === 'approve' && $id) {
    // CSRF Protection
    if (!Auth()->verifyCSRFToken($_GET['csrf_token'] ?? '')) {
        redirectWithMessage('affiliations.php', 'Security session expired. Please try again.', 'danger');
    }

    $app = $db->fetchOne("SELECT * FROM affiliation_applications WHERE id = ?", [$id]);
    if ($app && $app['application_status'] !== 'approved') {
        $name     = preg_replace('/[^A-Z0-9]/i', '', strtoupper($app['institution_name']));
        $username = 'CLG' . substr($name, 0, 5) . rand(100, 999);
        $password = 'Ibvte@' . rand(1000, 9999);
        $passHash = password_hash($password, PASSWORD_DEFAULT);
        $instCode = 'IBVTE' . date('Y') . str_pad($id, 4, '0', STR_PAD_LEFT);

        $userId = null;
        try {
            $userId = $db->insert('users', [
                'role_id'             => ROLE_COLLEGE,
                'username'            => $username,
                'email'               => $app['director_email'],
                'password'            => $passHash,
                'full_name'           => $app['director_name'],
                'mobile'              => $app['director_mobile'],
                'institution_name'    => $app['institution_name'],
                'institution_code'    => $instCode,
                'city'                => $app['city'],
                'state'               => $app['state'],
                'affiliation_status'  => 'approved',
                'is_active'           => 1,
                'created_at'          => date('Y-m-d H:i:s'),
            ]);
            $db->insert('wallets', [
                'user_id'     => $userId,
                'wallet_type' => 'college',
                'balance'     => 0,
                'created_at'  => date('Y-m-d H:i:s'),
            ]);
        } catch (Exception $e) {
            error_log("Affiliation Approval Error: " . $e->getMessage());
        }

        $db->update('affiliation_applications', [
            'application_status'  => 'approved',
            'approved_by'         => $admin['id'],
            'approved_at'         => date('Y-m-d H:i:s'),
            'approval_valid_from' => date('Y-m-d'),
            'approval_valid_until'=> date('Y-m-d', strtotime('+3 years')),
        ], ['id' => $id]);

        $_SESSION['cred_modal'] = [
            'username' => $username,
            'password' => $password,
            'inst'     => $app['institution_name'],
            'code'     => $instCode,
        ];
        redirectWithMessage('affiliations.php', "✅ Approved! College account created: <strong>$username</strong>", 'success');
    }
}

// ── REJECT ────────────────────────────────────────────────────────────────────
if ($action === 'reject' && $id) {
    // CSRF Protection
    if (!Auth()->verifyCSRFToken($_GET['csrf_token'] ?? '')) {
        redirectWithMessage('affiliations.php', 'Security session expired. Please try again.', 'danger');
    }

    $db->update('affiliation_applications', [
        'application_status' => 'rejected',
        'approved_by'        => $admin['id'],
        'approved_at'        => date('Y-m-d H:i:s'),
        'review_remarks'     => trim($_GET['reason'] ?? 'Rejected by admin'),
    ], ['id' => $id]);
    redirectWithMessage('affiliations.php', '❌ Application rejected.', 'warning');
}

// ── UNDER REVIEW ──────────────────────────────────────────────────────────────
if ($action === 'review' && $id) {
    // CSRF Protection
    if (!Auth()->verifyCSRFToken($_GET['csrf_token'] ?? '')) {
        redirectWithMessage('affiliations.php', 'Security session expired. Please try again.', 'danger');
    }

    $db->update('affiliation_applications', ['application_status' => 'under_review'], ['id' => $id]);
    redirectWithMessage('affiliations.php', '🔍 Marked as Under Review.', 'info');
}

// ── SAVE EDIT ─────────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_edit'])) {
    // CSRF Protection
    if (!Auth()->verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        redirectWithMessage('affiliations.php', 'Security session expired. Please try again.', 'danger');
    }

    $eid = intval($_POST['edit_id']);
    $db->update('affiliation_applications', [
        'institution_name' => trim($_POST['institution_name']),
        'director_name'    => trim($_POST['director_name']),
        'director_mobile'  => trim($_POST['director_mobile']),
        'director_email'   => trim($_POST['director_email']),
        'address'          => trim($_POST['address']),
        'city'             => trim($_POST['city']),
        'state'            => trim($_POST['state']),
        'review_remarks'   => trim($_POST['review_remarks']),
    ], ['id' => $eid]);
    redirectWithMessage('affiliations.php', '✏️ Application updated.', 'success');
}

// ── FETCH DATA ────────────────────────────────────────────────────────────────
$statusFilter = $_GET['status'] ?? '';
$sql    = "SELECT * FROM affiliation_applications";
$params = [];
if ($statusFilter) { $sql .= " WHERE application_status = ?"; $params[] = $statusFilter; }
$sql .= " ORDER BY created_at DESC";
$applications = $db->fetchAll($sql, $params);

$counts = [
    'all'          => $db->count('affiliation_applications'),
    'submitted'    => $db->count('affiliation_applications', ['application_status' => 'submitted']),
    'under_review' => $db->count('affiliation_applications', ['application_status' => 'under_review']),
    'approved'     => $db->count('affiliation_applications', ['application_status' => 'approved']),
    'rejected'     => $db->count('affiliation_applications', ['application_status' => 'rejected']),
];

$viewApp   = ($action === 'view' && $id) ? $db->fetchOne("SELECT * FROM affiliation_applications WHERE id = ?", [$id]) : null;
$credModal = $_SESSION['cred_modal'] ?? null;
unset($_SESSION['cred_modal']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Affiliation Applications – <?= APP_SHORT_NAME ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/admin-style.css" rel="stylesheet">
</head>
<body>
<?php include __DIR__ . '/../includes/admin_header.php'; ?>
<div class="container-fluid">
    <div class="row">
        <?php include __DIR__ . '/../includes/admin_sidebar.php'; ?>

        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">

            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2 class="h3"><i class="fas fa-file-signature me-2 text-primary"></i>Affiliation Applications</h2>
                <div>
                    <span class="badge bg-warning text-dark fs-6 me-2"><?= $counts['submitted'] ?> New</span>
                    <span class="badge bg-info fs-6"><?= $counts['under_review'] ?> Under Review</span>
                </div>
            </div>

            <?php if ($flash): ?>
                <div class="alert alert-<?= $flash['type'] ?> alert-dismissible fade show shadow-sm">
                    <?= htmlspecialchars($flash['message']) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <!-- Status Filter Tabs -->
            <ul class="nav nav-pills mb-4 flex-wrap gap-1">
                <li class="nav-item"><a class="nav-link <?= !$statusFilter ? 'active' : '' ?>" href="affiliations.php">All (<?= $counts['all'] ?>)</a></li>
                <li class="nav-item"><a class="nav-link <?= $statusFilter==='submitted'    ? 'active' : '' ?>" href="?status=submitted">📥 New (<?= $counts['submitted'] ?>)</a></li>
                <li class="nav-item"><a class="nav-link <?= $statusFilter==='under_review' ? 'active' : '' ?>" href="?status=under_review">🔍 Under Review (<?= $counts['under_review'] ?>)</a></li>
                <li class="nav-item"><a class="nav-link <?= $statusFilter==='approved'     ? 'active' : '' ?>" href="?status=approved">✅ Approved (<?= $counts['approved'] ?>)</a></li>
                <li class="nav-item"><a class="nav-link <?= $statusFilter==='rejected'     ? 'active' : '' ?>" href="?status=rejected">❌ Rejected (<?= $counts['rejected'] ?>)</a></li>
            </ul>

            <!-- Table -->
            <div class="card shadow-sm border-0" style="border-radius:15px;">
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="bg-light">
                                <tr>
                                    <th class="ps-3">App No.</th>
                                    <th>Institution</th>
                                    <th>Contact</th>
                                    <th>Location</th>
                                    <th>Status</th>
                                    <th>Submitted</th>
                                    <th class="text-end pe-3">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php if (empty($applications)): ?>
                                <tr><td colspan="7" class="text-center py-5 text-muted">
                                    <i class="fas fa-inbox fa-2x mb-2 d-block opacity-50"></i>No applications found.
                                </td></tr>
                            <?php endif; ?>
                            <?php foreach ($applications as $a):
                                $badge = match($a['application_status']) {
                                    'approved'     => 'bg-success',
                                    'rejected'     => 'bg-danger',
                                    'under_review' => 'bg-info',
                                    'submitted'    => 'bg-warning text-dark',
                                    default        => 'bg-secondary',
                                };
                                $label = match($a['application_status']) {
                                    'submitted'    => 'New',
                                    'under_review' => 'Under Review',
                                    'approved'     => 'Approved',
                                    'rejected'     => 'Rejected',
                                    default        => ucfirst($a['application_status']),
                                };
                            ?>
                            <tr>
                                <td class="ps-3">
                                    <span class="badge bg-dark"><?= htmlspecialchars($a['application_number'] ?? '#'.$a['id']) ?></span>
                                </td>
                                <td>
                                    <div class="fw-bold text-primary"><?= htmlspecialchars($a['institution_name']) ?></div>
                                    <small class="text-muted"><?= htmlspecialchars(ucfirst($a['institution_type'] ?? '')) ?></small>
                                </td>
                                <td>
                                    <div><?= htmlspecialchars($a['director_name']) ?></div>
                                    <small class="text-muted"><?= htmlspecialchars($a['director_mobile']) ?></small><br>
                                    <small class="text-muted"><?= htmlspecialchars($a['director_email']) ?></small>
                                </td>
                                <td><small><?= htmlspecialchars(($a['city'] ?? '') . ', ' . ($a['state'] ?? '')) ?></small></td>
                                <td><span class="badge <?= $badge ?>"><?= $label ?></span></td>
                                <td><small><?= $a['submitted_at'] ? date('d M Y', strtotime($a['submitted_at'])) : date('d M Y', strtotime($a['created_at'])) ?></small></td>
                                <td class="text-end pe-3">
                                    <div class="btn-group btn-group-sm">
                                        <a href="?action=view&id=<?= $a['id'] ?>" class="btn btn-outline-primary" title="View Details">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <button class="btn btn-outline-secondary" title="Edit"
                                                onclick='openEdit(<?= json_encode($a) ?>)'>
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <?php if (in_array($a['application_status'], ['submitted','under_review'])): ?>
                                        <a href="?action=review&id=<?= $a['id'] ?>&csrf_token=<?= Auth()->generateCSRFToken() ?>" class="btn btn-outline-info" title="Mark Under Review">
                                            <i class="fas fa-search"></i>
                                        </a>
                                        <a href="?action=approve&id=<?= $a['id'] ?>&csrf_token=<?= Auth()->generateCSRFToken() ?>" class="btn btn-success" title="Approve"
                                           onclick="return confirm('Approve and create college login account?')">
                                            <i class="fas fa-check"></i>
                                        </a>
                                        <a href="?action=reject&id=<?= $a['id'] ?>&csrf_token=<?= Auth()->generateCSRFToken() ?>" class="btn btn-danger" title="Reject"
                                           onclick="return confirm('Reject this application?')">
                                            <i class="fas fa-times"></i>
                                        </a>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Detail Panel -->
            <?php if ($viewApp): ?>
            <div class="card mt-4 shadow border-0" style="border-radius:15px;">
                <div class="card-header d-flex justify-content-between align-items-center"
                     style="background:linear-gradient(135deg,#3b0b7c,#6c4ab6);color:white;border-radius:15px 15px 0 0;">
                    <h5 class="mb-0"><i class="fas fa-university me-2"></i><?= htmlspecialchars($viewApp['institution_name']) ?>
                        &nbsp;<small class="badge bg-light text-dark"><?= htmlspecialchars($viewApp['application_number'] ?? '#'.$viewApp['id']) ?></small>
                    </h5>
                    <a href="affiliations.php" class="btn btn-sm btn-light">✕ Close</a>
                </div>
                <div class="card-body">
                    <div class="row g-4">
                        <div class="col-md-6">
                            <h6 class="text-primary fw-bold border-bottom pb-1 mb-3">Institution Info</h6>
                            <table class="table table-sm table-borderless">
                                <tr><td class="text-muted w-40">Type</td><td><?= htmlspecialchars(ucfirst($viewApp['institution_type'] ?? '-')) ?></td></tr>
                                <tr><td class="text-muted">Est. Year</td><td><?= htmlspecialchars($viewApp['established_year'] ?? '-') ?></td></tr>
                                <tr><td class="text-muted">Total Staff</td><td><?= htmlspecialchars($viewApp['total_staff'] ?? '-') ?></td></tr>
                                <tr><td class="text-muted">Classrooms</td><td><?= htmlspecialchars($viewApp['number_of_classrooms'] ?? '-') ?></td></tr>
                                <tr><td class="text-muted">Library</td><td><?= $viewApp['library_facility'] ? '<span class="badge bg-success">Yes</span>' : '<span class="badge bg-secondary">No</span>' ?></td></tr>
                                <tr><td class="text-muted">Computer Lab</td><td><?= $viewApp['computer_lab'] ? '<span class="badge bg-success">Yes</span>' : '<span class="badge bg-secondary">No</span>' ?></td></tr>
                                <tr><td class="text-muted">Internet</td><td><?= $viewApp['internet_facility'] ? '<span class="badge bg-success">Yes</span>' : '<span class="badge bg-secondary">No</span>' ?></td></tr>
                                <tr><td class="text-muted">Courses</td><td><small><?= htmlspecialchars($viewApp['courses_applied'] ?? '-') ?></small></td></tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <h6 class="text-primary fw-bold border-bottom pb-1 mb-3">Contact & Address</h6>
                            <table class="table table-sm table-borderless">
                                <tr><td class="text-muted w-40">Director</td><td><strong><?= htmlspecialchars($viewApp['director_name']) ?></strong></td></tr>
                                <tr><td class="text-muted">Mobile</td><td><?= htmlspecialchars($viewApp['director_mobile']) ?></td></tr>
                                <tr><td class="text-muted">Email</td><td><?= htmlspecialchars($viewApp['director_email']) ?></td></tr>
                                <tr><td class="text-muted">Address</td><td><?= htmlspecialchars($viewApp['address'] ?? '-') ?></td></tr>
                                <tr><td class="text-muted">City/State</td><td><?= htmlspecialchars(($viewApp['city'] ?? '') . ', ' . ($viewApp['state'] ?? '')) ?></td></tr>
                                <tr><td class="text-muted">Pincode</td><td><?= htmlspecialchars($viewApp['pincode'] ?? '-') ?></td></tr>
                                <tr><td class="text-muted">Txn Ref</td><td><?= htmlspecialchars($viewApp['affiliation_fee_transaction_id'] ?? '-') ?></td></tr>
                            </table>
                        </div>
                    </div>
                    <?php if ($viewApp['review_remarks']): ?>
                    <div class="alert alert-warning"><strong>Admin Remarks:</strong> <?= htmlspecialchars($viewApp['review_remarks']) ?></div>
                    <?php endif; ?>
                    <?php if (in_array($viewApp['application_status'], ['submitted','under_review'])): ?>
                    <div class="d-flex gap-2 mt-3">
                        <a href="?action=approve&id=<?= $viewApp['id'] ?>&csrf_token=<?= Auth()->generateCSRFToken() ?>" class="btn btn-success"
                           onclick="return confirm('Approve and create college account?')">
                            <i class="fas fa-check me-1"></i>Approve Application
                        </a>
                        <a href="?action=reject&id=<?= $viewApp['id'] ?>&csrf_token=<?= Auth()->generateCSRFToken() ?>" class="btn btn-danger"
                           onclick="return confirm('Reject this application?')">
                            <i class="fas fa-times me-1"></i>Reject
                        </a>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>

        </main>
    </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?= Auth()->generateCSRFToken() ?>">
                <div class="modal-header" style="background:linear-gradient(135deg,#3b0b7c,#6c4ab6);color:white;">
                    <h5 class="modal-title"><i class="fas fa-edit me-2"></i>Edit Application</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="edit_id" id="edit_id">
                    <div class="row g-3">
                        <div class="col-12"><label class="fw-bold">Institution Name</label>
                            <input type="text" name="institution_name" id="ei_name" class="form-control"></div>
                        <div class="col-md-6"><label class="fw-bold">Director Name</label>
                            <input type="text" name="director_name" id="ei_dir" class="form-control"></div>
                        <div class="col-md-6"><label class="fw-bold">Mobile</label>
                            <input type="text" name="director_mobile" id="ei_mob" class="form-control"></div>
                        <div class="col-12"><label class="fw-bold">Email</label>
                            <input type="email" name="director_email" id="ei_email" class="form-control"></div>
                        <div class="col-12"><label class="fw-bold">Address</label>
                            <textarea name="address" id="ei_addr" class="form-control" rows="2"></textarea></div>
                        <div class="col-md-6"><label class="fw-bold">City</label>
                            <input type="text" name="city" id="ei_city" class="form-control"></div>
                        <div class="col-md-6"><label class="fw-bold">State</label>
                            <input type="text" name="state" id="ei_state" class="form-control"></div>
                        <div class="col-12"><label class="fw-bold">Admin Remarks</label>
                            <textarea name="review_remarks" id="ei_remarks" class="form-control" rows="2" placeholder="Internal notes..."></textarea></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="save_edit" class="btn btn-primary"><i class="fas fa-save me-1"></i>Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Credentials Modal (auto-show after approve) -->
<?php if ($credModal): ?>
<div class="modal fade" id="newCredModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title">🎉 College Account Created!</h5>
            </div>
            <div class="modal-body text-center py-4">
                <h6 class="mb-3"><?= htmlspecialchars($credModal['inst']) ?></h6>
                <table class="table table-bordered">
                    <tr><td class="text-muted">Institution Code</td><td><strong><?= htmlspecialchars($credModal['code']) ?></strong></td></tr>
                    <tr><td class="text-muted">Username</td><td><strong class="text-primary"><?= htmlspecialchars($credModal['username']) ?></strong></td></tr>
                    <tr><td class="text-muted">Password</td><td><strong class="text-danger"><?= htmlspecialchars($credModal['password']) ?></strong></td></tr>
                </table>
                <div class="alert alert-warning text-start small mb-0">⚠️ Save these now — password won't be shown again in plain text.</div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-success" data-bs-dismiss="modal"><i class="fas fa-check me-1"></i>I've Saved the Credentials</button>
            </div>
        </div>
    </div>
</div>
<script>window.addEventListener('DOMContentLoaded',function(){new bootstrap.Modal(document.getElementById('newCredModal')).show();});</script>
<?php endif; ?>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
function openEdit(a) {
    document.getElementById('edit_id').value    = a.id;
    document.getElementById('ei_name').value    = a.institution_name;
    document.getElementById('ei_dir').value     = a.director_name;
    document.getElementById('ei_mob').value     = a.director_mobile;
    document.getElementById('ei_email').value   = a.director_email;
    document.getElementById('ei_addr').value    = a.address || '';
    document.getElementById('ei_city').value    = a.city    || '';
    document.getElementById('ei_state').value   = a.state   || '';
    document.getElementById('ei_remarks').value = a.review_remarks || '';
    new bootstrap.Modal(document.getElementById('editModal')).show();
}
</script>
</body>
</html>