<?php
declare(strict_types=1);

require_once __DIR__ . "/../../config/db.php";
require_once __DIR__ . "/../../config/auth.php";

require_admin();

$success = "";
$error = "";

/**
 * Helper: fetchAll
 */
function fetchAll(PDO $pdo, string $sql, array $params = []): array {
    $st = $pdo->prepare($sql);
    $st->execute($params);
    return $st->fetchAll(PDO::FETCH_ASSOC);
}

/**
 * Transfer GP from one REP to another
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'transfer_gp') {
    if (!csrf_validate($_POST['csrf'] ?? '')) {
        $error = "Invalid request.";
    } else {
        $gp_id = strtoupper(trim($_POST['gp_id'] ?? ''));
        $from_rep_id = (int)($_POST['from_rep_id'] ?? 0);
        $to_rep_id = (int)($_POST['to_rep_id'] ?? 0);
        $reason = trim($_POST['reason'] ?? 'Transfer');
        
        try {
            $pdo->beginTransaction();
            
            // ========== STEP 1: CLEANUP ==========
            // প্রথমে এই GP-র সব INACTIVE records ডিলিট করুন
            $stCleanup = $pdo->prepare("
                DELETE FROM gp_assignments 
                WHERE gp_id = ? AND status = 'INACTIVE'
            ");
            $stCleanup->execute([$gp_id]);
            
            // ========== STEP 2: GET SCHOOL STATISTICS ==========
            // Get all schools under this GP and their visit status for current REP
            $stSchools = $pdo->prepare("
                SELECT 
                    s.id,
                    s.name,
                    CASE 
                        WHEN EXISTS (
                            SELECT 1 FROM school_visits vs 
                            WHERE vs.school_id = s.id AND vs.representative_id = ?
                        ) THEN 1 ELSE 0 
                    END as is_visited,
                    (
                        SELECT MAX(vs.visited_at) FROM school_visits vs 
                        WHERE vs.school_id = s.id AND vs.representative_id = ?
                    ) as last_visit_date
                FROM schools s
                WHERE s.gp_id = ?
                ORDER BY s.name
            ");
            $stSchools->execute([$from_rep_id, $from_rep_id, $gp_id]);
            $schools = $stSchools->fetchAll(PDO::FETCH_ASSOC);
            
            // ========== STEP 3: CALCULATE STATISTICS ==========
            $totalSchools = count($schools);
            $visitedSchools = 0;
            $neverVisited = 0;
            $visitedSchoolIds = [];
            
            foreach ($schools as $school) {
                if ($school['is_visited'] == 1) {
                    $visitedSchools++;
                    $visitedSchoolIds[] = $school['id'];
                } else {
                    $neverVisited++;
                }
            }
            
            // ========== STEP 4: CHECK CURRENT ACTIVE ASSIGNMENT ==========
            $stCheckActive = $pdo->prepare("
                SELECT id, user_id 
                FROM gp_assignments 
                WHERE gp_id = ? AND status = 'ACTIVE'
                LIMIT 1
            ");
            $stCheckActive->execute([$gp_id]);
            $activeAssignment = $stCheckActive->fetch(PDO::FETCH_ASSOC);
            
            // ========== STEP 5: HANDLE CURRENT ASSIGNMENT ==========
            if ($activeAssignment) {
                if ($activeAssignment['user_id'] != $to_rep_id) {
                    $stDeactivate = $pdo->prepare("
                        UPDATE gp_assignments 
                        SET status = 'INACTIVE', 
                            deactivated_at = NOW(),
                            deactivation_reason = ?
                        WHERE id = ?
                    ");
                    $stDeactivate->execute([$reason, $activeAssignment['id']]);
                } else {
                    $pdo->commit();
                    $success = "GP already assigned to this REP.";
                    return;
                }
            }
            
            // ========== STEP 6: DOUBLE CLEANUP ==========
            $stCleanupAgain = $pdo->prepare("
                DELETE FROM gp_assignments 
                WHERE gp_id = ? AND status = 'INACTIVE'
            ");
            $stCleanupAgain->execute([$gp_id]);
            
            // ========== STEP 7: CREATE NEW ASSIGNMENT ==========
            $stGetBlock = $pdo->prepare("SELECT block_id FROM gps WHERE id = ?");
            $stGetBlock->execute([$gp_id]);
            $block_id = $stGetBlock->fetchColumn();
            
            if (!$block_id) {
                throw new RuntimeException("Invalid GP ID");
            }
            
            // Insert new active assignment
            $stInsert = $pdo->prepare("
                INSERT INTO gp_assignments 
                    (block_id, gp_id, user_id, status, assigned_on, transferred_from, deactivation_reason)
                VALUES (?, ?, ?, 'ACTIVE', NOW(), ?, ?)
            ");
            $stInsert->execute([$block_id, $gp_id, $to_rep_id, $from_rep_id, $reason]);
            
            // ========== STEP 8: LOG THE TRANSFER ==========
            $stLog = $pdo->prepare("
                INSERT INTO assignment_transfers 
                    (gp_id, from_rep_id, to_rep_id, transfer_date, 
                     total_schools, visited_schools, pending_schools, 
                     visited_school_ids, reason)
                VALUES (?, ?, ?, NOW(), ?, ?, ?, ?, ?)
            ");
            $stLog->execute([
                $gp_id, 
                $from_rep_id, 
                $to_rep_id, 
                $totalSchools,
                $visitedSchools,
                $neverVisited,
                json_encode($visitedSchoolIds),
                $reason
            ]);
            
            $pdo->commit();
            
            // ========== STEP 9: SUCCESS MESSAGE ==========
            $success = "
                <div class='alert alert-success alert-dismissible fade show' role='alert'>
                    <button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>
                    <h6 class='alert-heading'><i class='bi bi-check-circle-fill'></i> GP Successfully Transferred!</h6>
                    <hr>
                    <table class='table table-sm table-borderless mb-0'>
                        <tr>
                            <td><strong>GP:</strong></td>
                            <td>{$gp_id}</td>
                        </tr>
                        <tr>
                            <td><strong>From REP:</strong></td>
                            <td>ID {$from_rep_id}</td>
                        </tr>
                        <tr>
                            <td><strong>To REP:</strong></td>
                            <td>ID {$to_rep_id}</td>
                        </tr>
                        <tr>
                            <td><strong>Total Schools:</strong></td>
                            <td>{$totalSchools}</td>
                        </tr>
                        <tr>
                            <td><strong>Previously Visited:</strong></td>
                            <td>{$visitedSchools} <span class='text-muted'>(Completed by previous REP)</span></td>
                        </tr>
                        <tr>
                            <td><strong>Pending Schools:</strong></td>
                            <td>{$neverVisited} <span class='text-warning'>(Will show in new REP's list)</span></td>
                        </tr>
                    </table>
                    <small class='text-muted'><i class='bi bi-info-circle'></i> Only pending schools will appear in the new REP's school list</small>
                </div>
            ";
            
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            $error = "Transfer failed: " . $e->getMessage();
        }
    }
}

/**
 * Bulk assignments
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'assign_bulk') {
    if (!csrf_validate($_POST['csrf'] ?? '')) {
        $error = "Invalid request.";
    } else {
        $user_id = (int)($_POST['user_id'] ?? 0);
        $block_id = strtoupper(trim((string)($_POST['block_id'] ?? '')));
        $gp_ids = $_POST['gp_ids'] ?? [];

        if ($user_id <= 0 || $block_id === '' || !is_array($gp_ids) || count($gp_ids) === 0) {
            $error = "Please select Rep, Block and at least one GP.";
        } else {
            try {
                $pdo->beginTransaction();

                // Validate user is REP and active
                $st = $pdo->prepare("SELECT role, active FROM users WHERE id=? LIMIT 1");
                $st->execute([$user_id]);
                $urow = $st->fetch(PDO::FETCH_ASSOC);

                if (!$urow || ($urow['role'] ?? '') !== 'REP' || (int)($urow['active'] ?? 0) !== 1) {
                    throw new RuntimeException("Invalid Rep selected.");
                }

                // Clean up INACTIVE records
                $placeholders = implode(',', array_fill(0, count($gp_ids), '?'));
                $stCleanup = $pdo->prepare("
                    DELETE FROM gp_assignments 
                    WHERE gp_id IN ($placeholders) AND status = 'INACTIVE'
                ");
                $stCleanup->execute($gp_ids);

                // Check for GPs already assigned to OTHER reps
                $stCheckExisting = $pdo->prepare("
                    SELECT g.id, g.name, u.name as current_rep_name 
                    FROM gps g
                    LEFT JOIN gp_assignments ga ON g.id = ga.gp_id AND ga.status = 'ACTIVE'
                    LEFT JOIN users u ON ga.user_id = u.id
                    WHERE g.id IN ($placeholders) AND ga.user_id IS NOT NULL AND ga.user_id != ?
                ");
                
                $params = array_merge($gp_ids, [$user_id]);
                $stCheckExisting->execute($params);
                $alreadyAssigned = $stCheckExisting->fetchAll(PDO::FETCH_ASSOC);
                
                if (!empty($alreadyAssigned)) {
                    foreach ($alreadyAssigned as $conflict) {
                        $stDeactivate = $pdo->prepare("
                            UPDATE gp_assignments 
                            SET status = 'INACTIVE',
                                deactivated_at = NOW(),
                                deactivation_reason = 'Auto-deactivated for reassignment'
                            WHERE gp_id = ? AND status = 'ACTIVE'
                        ");
                        $stDeactivate->execute([$conflict['id']]);
                    }
                }

                // Validate each GP belongs to selected block
                $stCheckGP = $pdo->prepare("SELECT 1 FROM gps WHERE id=? AND block_id=? LIMIT 1");

                // Insert new assignments
                $stInsert = $pdo->prepare("
                    INSERT INTO gp_assignments (block_id, gp_id, user_id, status, assigned_on)
                    VALUES (?, ?, ?, 'ACTIVE', ?)
                ");

                $today = date('Y-m-d');
                $assignedCount = 0;
                $skippedCount = 0;

                foreach ($gp_ids as $gp_id_raw) {
                    $gp_id = strtoupper(trim((string)$gp_id_raw));
                    if ($gp_id === '') continue;

                    $stCheckGP->execute([$gp_id, $block_id]);
                    if (!$stCheckGP->fetchColumn()) {
                        $skippedCount++;
                        continue;
                    }

                    $stCheckActive = $pdo->prepare("
                        SELECT id FROM gp_assignments 
                        WHERE gp_id = ? AND status = 'ACTIVE'
                    ");
                    $stCheckActive->execute([$gp_id]);
                    
                    if (!$stCheckActive->fetch()) {
                        $stInsert->execute([$block_id, $gp_id, $user_id, $today]);
                        $assignedCount++;
                    } else {
                        $skippedCount++;
                    }
                }

                $pdo->commit();
                
                $success = "Assigned successfully. GPs assigned: {$assignedCount}" . 
                          ($skippedCount > 0 ? " (Skipped {$skippedCount} - already assigned)" : "");
                
            } catch (Throwable $e) {
                if ($pdo->inTransaction()) $pdo->rollBack();
                $error = "Assignment failed: " . $e->getMessage();
            }
        }
    }
}

/**
 * Toggle assignment status
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'toggle_status') {
    if (!csrf_validate($_POST['csrf'] ?? '')) {
        $error = "Invalid request.";
    } else {
        $assign_id = (int)($_POST['assign_id'] ?? 0);
        if ($assign_id <= 0) {
            $error = "Invalid assignment.";
        } else {
            try {
                $pdo->beginTransaction();
                
                $stGet = $pdo->prepare("SELECT gp_id, status, user_id FROM gp_assignments WHERE id=?");
                $stGet->execute([$assign_id]);
                $current = $stGet->fetch(PDO::FETCH_ASSOC);
                
                if (!$current) {
                    throw new RuntimeException("Assignment not found.");
                }
                
                if ($current['status'] === 'INACTIVE') {
                    // Check for conflicts when activating
                    $stCheck = $pdo->prepare("
                        SELECT id, user_id 
                        FROM gp_assignments 
                        WHERE gp_id = ? AND status = 'ACTIVE' AND id != ?
                    ");
                    $stCheck->execute([$current['gp_id'], $assign_id]);
                    $conflict = $stCheck->fetch(PDO::FETCH_ASSOC);
                    
                    if ($conflict) {
                        $stDeactivateConflict = $pdo->prepare("
                            UPDATE gp_assignments 
                            SET status = 'INACTIVE', 
                                deactivated_at = NOW(),
                                deactivation_reason = 'Auto-deactivated due to conflict'
                            WHERE id = ?
                        ");
                        $stDeactivateConflict->execute([$conflict['id']]);
                    }
                    
                    // Clean up INACTIVE records
                    $stCleanup = $pdo->prepare("
                        DELETE FROM gp_assignments 
                        WHERE gp_id = ? AND status = 'INACTIVE' AND id != ?
                    ");
                    $stCleanup->execute([$current['gp_id'], $assign_id]);
                    
                    $stUpdate = $pdo->prepare("UPDATE gp_assignments SET status = 'ACTIVE' WHERE id=?");
                    $stUpdate->execute([$assign_id]);
                    
                } else {
                    $stUpdate = $pdo->prepare("UPDATE gp_assignments SET status = 'INACTIVE', deactivated_at = NOW() WHERE id=?");
                    $stUpdate->execute([$assign_id]);
                }
                
                $pdo->commit();
                $success = "Assignment status updated successfully.";
                
            } catch (Throwable $e) {
                if ($pdo->inTransaction()) $pdo->rollBack();
                $error = "Failed: " . $e->getMessage();
            }
        }
    }
}

/**
 * Get all data for dropdowns
 */
$districts = fetchAll($pdo, "SELECT id, name FROM districts ORDER BY name ASC");
$reps = fetchAll($pdo, "SELECT id, name, email FROM users WHERE role='REP' AND active=1 ORDER BY name ASC");

/**
 * Get active GPs with statistics - শুধুমাত্র পেন্ডিং স্কুলগুলো কাউন্ট করবে
 */
$activeGPs = fetchAll($pdo, "
    SELECT 
        g.id, 
        g.name, 
        b.name as block_name,
        b.id as block_id,
        d.name as district_name,
        u.id as rep_id, 
        u.name as rep_name,
        u.email as rep_email,
        COUNT(DISTINCT s.id) as total_schools,
        COUNT(DISTINCT CASE 
            WHEN NOT EXISTS (
                SELECT 1 FROM school_visits vs 
                WHERE vs.school_id = s.id AND vs.representative_id = u.id
            ) THEN s.id 
        END) as pending_schools,
        COUNT(DISTINCT CASE 
            WHEN EXISTS (
                SELECT 1 FROM school_visits vs 
                WHERE vs.school_id = s.id AND vs.representative_id = u.id
            ) THEN s.id 
        END) as visited_schools
    FROM gp_assignments ga
    JOIN gps g ON ga.gp_id = g.id
    JOIN blocks b ON g.block_id = b.id
    JOIN districts d ON b.district_id = d.id
    JOIN users u ON ga.user_id = u.id
    LEFT JOIN schools s ON s.gp_id = g.id
    WHERE ga.status = 'ACTIVE'
    GROUP BY g.id, u.id, b.id, d.id
    ORDER BY d.name, b.name, g.name
");

/**
 * Filters
 */
$filter_district = strtoupper(trim((string)($_GET['district_id'] ?? '')));
$filter_block = strtoupper(trim((string)($_GET['block_id'] ?? '')));

$blocks = [];
if ($filter_district !== '') {
    $blocks = fetchAll($pdo, "SELECT id, name FROM blocks WHERE district_id=? ORDER BY name ASC", [$filter_district]);
}

/**
 * Current assignments - শুধুমাত্র পেন্ডিং স্কুলগুলো দেখাবে
 */
$where = "ga.status = 'ACTIVE'";
$params = [];

if ($filter_district !== '') {
    $where .= " AND d.id = ?";
    $params[] = $filter_district;
}
if ($filter_block !== '') {
    $where .= " AND ga.block_id = ?";
    $params[] = $filter_block;
}

$assignments = fetchAll($pdo, "
    SELECT
        ga.id, ga.status, ga.assigned_on,
        u.id AS rep_id, u.name AS rep_name, u.email AS rep_email,
        g.id AS gp_id, g.name AS gp_name,
        b.id AS block_id, b.name AS block_name,
        d.id AS district_id, d.name AS district_name,
        COUNT(DISTINCT s.id) as total_schools,
        COUNT(DISTINCT CASE 
            WHEN NOT EXISTS (
                SELECT 1 FROM school_visits vs 
                WHERE vs.school_id = s.id AND vs.representative_id = u.id
            ) THEN s.id 
        END) as pending_schools,
        COUNT(DISTINCT CASE 
            WHEN EXISTS (
                SELECT 1 FROM school_visits vs 
                WHERE vs.school_id = s.id AND vs.representative_id = u.id
            ) THEN s.id 
        END) as visited_schools
    FROM gp_assignments ga
    JOIN users u ON u.id = ga.user_id
    JOIN gps g ON g.id = ga.gp_id
    JOIN blocks b ON b.id = ga.block_id
    LEFT JOIN districts d ON d.id = b.district_id
    LEFT JOIN schools s ON s.gp_id = g.id
    WHERE {$where}
    GROUP BY ga.id, u.id, g.id, b.id, d.id
    ORDER BY d.name ASC, b.name ASC, g.name ASC
", $params);

/**
 * Transfer history
 */
$transfers = fetchAll($pdo, "
    SELECT 
        t.*, 
        g.name as gp_name,
        u1.name as from_rep_name,
        u2.name as to_rep_name,
        u2.email as to_rep_email
    FROM assignment_transfers t
    JOIN gps g ON t.gp_id = g.id
    JOIN users u1 ON t.from_rep_id = u1.id
    JOIN users u2 ON t.to_rep_id = u2.id
    ORDER BY t.transfer_date DESC
    LIMIT 50
");

$page_title = "Admin - GP Assignments";
require_once __DIR__ . "/../partials/header.php";
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $page_title ?></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <style>
        .card-soft { border-radius: 12px; border: none; }
        .shadow-soft { box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
        .table th { font-weight: 600; color: #495057; border-bottom-width: 1px; }
        .badge { font-weight: 500; padding: 0.35em 0.65em; }
        .progress { background-color: #e9ecef; border-radius: 10px; }
        .btn-sm { padding: 0.25rem 0.5rem; font-size: 0.75rem; }
        .stat-card { transition: transform 0.2s; }
        .stat-card:hover { transform: translateY(-2px); }
    </style>
</head>
<body>
    <div class="container-fluid py-3">
        <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-2 mb-3">
            <div>
                <h5 class="mb-0"><i class="bi bi-diagram-3"></i> GP Assignments</h5>
                <div class="text-muted small">Only pending schools show in REP's list after transfer</div>
            </div>
            <div class="d-flex gap-2">
                <a class="btn btn-outline-dark btn-sm" href="/school-crm/public/admin/users.php"><i class="bi bi-people"></i> Users</a>
                <a class="btn btn-outline-dark btn-sm" href="/school-crm/public/admin/districts.php"><i class="bi bi-map"></i> Districts</a>
                <a class="btn btn-outline-primary btn-sm" href="/school-crm/public/admin/rep_visit_report.php"><i class="bi bi-bar-chart"></i> Visit Report</a>
            </div>
        </div>

        <?php if ($success): ?>
            <?= $success ?>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="alert alert-danger alert-dismissible fade show py-2" role="alert">
                <i class="bi bi-exclamation-triangle-fill"></i> <?= htmlspecialchars($error) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Transfer GP Form -->
        <div class="card card-soft shadow-soft p-3 p-md-4 mb-3">
            <h6 class="mb-3">
                <i class="bi bi-arrow-left-right text-warning"></i> Transfer GP to Another REP
            </h6>
            
            <form method="post" class="row g-3" id="transferForm">
                <input type="hidden" name="csrf" value="<?= htmlspecialchars(csrf_token()) ?>">
                <input type="hidden" name="action" value="transfer_gp">
                <input type="hidden" name="from_rep_id" id="fromRepId">
                
                <div class="col-12 col-md-5">
                    <label class="form-label fw-semibold">Select GP to Transfer <span class="text-danger">*</span></label>
                    <select class="form-select" name="gp_id" id="gpSelect" required>
                        <option value="">-- Choose GP --</option>
                        <?php foreach ($activeGPs as $gp): ?>
                            <option value="<?= htmlspecialchars($gp['id']) ?>" 
                                    data-rep-id="<?= $gp['rep_id'] ?>"
                                    data-rep-name="<?= htmlspecialchars($gp['rep_name']) ?>"
                                    data-total="<?= $gp['total_schools'] ?>"
                                    data-visited="<?= $gp['visited_schools'] ?>"
                                    data-pending="<?= $gp['pending_schools'] ?>"
                                    data-block="<?= htmlspecialchars($gp['block_name']) ?>"
                                    data-district="<?= htmlspecialchars($gp['district_name']) ?>">
                                <?= htmlspecialchars($gp['name']) ?> 
                                (<?= htmlspecialchars($gp['district_name']) ?> - <?= htmlspecialchars($gp['block_name']) ?>) 
                                [<?= htmlspecialchars($gp['rep_name']) ?>]
                                (Pending: <?= $gp['pending_schools'] ?>/<?= $gp['total_schools'] ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-12 col-md-5">
                    <label class="form-label fw-semibold">Transfer to New REP <span class="text-danger">*</span></label>
                    <select class="form-select" name="to_rep_id" id="toRepSelect" required>
                        <option value="">-- Select New REP --</option>
                        <?php foreach ($reps as $r): ?>
                            <option value="<?= (int)$r['id'] ?>">
                                <?= htmlspecialchars($r['name']) ?> (<?= htmlspecialchars($r['email']) ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-12 col-md-2">
                    <label class="form-label fw-semibold">Reason</label>
                    <select class="form-select" name="reason">
                        <option value="Performance Issue">Performance</option>
                        <option value="Resignation">Resignation</option>
                        <option value="Territory Change">Territory Change</option>
                        <option value="Promotion">Promotion</option>
                        <option value="Other">Other</option>
                    </select>
                </div>
                
                <!-- Statistics Display -->
                <div class="col-12" id="gpStats" style="display: none;">
                    <div class="card bg-light border-primary">
                        <div class="card-body py-2">
                            <div class="row">
                                <div class="col-md-3">
                                    <small class="text-muted">Current REP</small>
                                    <div class="fw-bold" id="currentRepName">-</div>
                                </div>
                                <div class="col-md-3">
                                    <small class="text-muted">Location</small>
                                    <div class="fw-bold" id="gpLocation">-</div>
                                </div>
                                <div class="col-md-2">
                                    <small class="text-muted">Total Schools</small>
                                    <div class="fw-bold" id="totalSchools">0</div>
                                </div>
                                <div class="col-md-2">
                                    <small class="text-muted text-success">Visited</small>
                                    <div class="fw-bold text-success" id="visitedSchools">0</div>
                                </div>
                                <div class="col-md-2">
                                    <small class="text-muted text-warning">Pending</small>
                                    <div class="fw-bold text-warning" id="pendingSchools">0</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Transfer Warning -->
                <div class="col-12" id="transferWarning" style="display: none;">
                    <div class="alert alert-warning py-2">
                        <i class="bi bi-exclamation-triangle-fill"></i>
                        <span id="warningMessage"></span>
                        <br>
                        <small><i class="bi bi-info-circle"></i> Only <span id="pendingCount">0</span> pending schools will appear in new REP's list. Visited schools remain with previous REP's history.</small>
                    </div>
                </div>
                
                <div class="col-12">
                    <button type="submit" class="btn btn-warning" onclick="return confirmTransfer()">
                        <i class="bi bi-arrow-left-right"></i> Transfer GP
                    </button>
                    <button type="reset" class="btn btn-outline-secondary">Clear</button>
                </div>
            </form>
        </div>

        <!-- Bulk Assign Form -->
        <div class="card card-soft shadow-soft p-3 p-md-4 mb-3">
            <h6 class="mb-3">
                <i class="bi bi-plus-circle text-primary"></i> Assign Multiple GPs to REP
            </h6>
            
            <form method="post" class="row g-3" id="assignForm">
                <input type="hidden" name="csrf" value="<?= htmlspecialchars(csrf_token()) ?>">
                <input type="hidden" name="action" value="assign_bulk">

                <div class="col-12 col-md-4">
                    <label class="form-label fw-semibold">Select REP <span class="text-danger">*</span></label>
                    <select class="form-select" name="user_id" required>
                        <option value="">-- Choose REP --</option>
                        <?php foreach ($reps as $r): ?>
                            <option value="<?= (int)$r['id'] ?>">
                                <?= htmlspecialchars($r['name']) ?> (<?= htmlspecialchars($r['email']) ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-12 col-md-4">
                    <label class="form-label fw-semibold">District <span class="text-danger">*</span></label>
                    <select class="form-select" id="districtSel" required>
                        <option value="">-- Select District --</option>
                        <?php foreach ($districts as $d): ?>
                            <option value="<?= htmlspecialchars($d['id']) ?>">
                                <?= htmlspecialchars($d['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-12 col-md-4">
                    <label class="form-label fw-semibold">Block <span class="text-danger">*</span></label>
                    <select class="form-select" name="block_id" id="blockSel" required disabled>
                        <option value="">-- Select Block --</option>
                    </select>
                </div>

                <div class="col-12">
                    <label class="form-label fw-semibold">Select GPs (Multiple) <span class="text-danger">*</span></label>
                    <select class="form-select" name="gp_ids[]" id="gpSel" multiple size="8" disabled required></select>
                    <small class="text-muted"><i class="bi bi-info-circle"></i> Hold Ctrl/Cmd to select multiple GPs</small>
                </div>

                <div class="col-12 text-end">
                    <button type="submit" class="btn btn-dark px-4">
                        <i class="bi bi-check-circle"></i> Assign Selected GPs
                    </button>
                </div>
            </form>
        </div>

        <!-- Current Assignments List - shows only pending counts -->
        <div class="card card-soft shadow-soft p-3 p-md-4 mb-3">
            <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-2 mb-3">
                <h6 class="mb-0">
                    <i class="bi bi-list-check text-success"></i> Current Active Assignments
                    <small class="text-muted">(Showing pending schools only)</small>
                </h6>

                <form method="get" class="d-flex flex-wrap gap-2">
                    <select class="form-select form-select-sm" name="district_id" id="filterDistrict" style="width:200px;">
                        <option value="">All Districts</option>
                        <?php foreach ($districts as $d): ?>
                            <option value="<?= htmlspecialchars($d['id']) ?>" <?= $filter_district === $d['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($d['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>

                    <select class="form-select form-select-sm" name="block_id" id="filterBlock" style="width:200px;" <?= !$filter_district ? 'disabled' : '' ?>>
                        <option value="">All Blocks</option>
                        <?php foreach ($blocks as $b): ?>
                            <option value="<?= htmlspecialchars($b['id']) ?>" <?= $filter_block === $b['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($b['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>

                    <button type="submit" class="btn btn-sm btn-outline-dark"><i class="bi bi-funnel"></i> Filter</button>
                    <a href="/school-crm/public/admin/gp_assignments.php" class="btn btn-sm btn-outline-secondary"><i class="bi bi-eraser"></i> Clear</a>
                </form>
            </div>

            <div class="table-responsive">
                <table class="table table-striped table-hover align-middle mb-0">
                    <thead>
                        <tr>
                            <th>Status</th>
                            <th>District</th>
                            <th>Block</th>
                            <th>GP</th>
                            <th>REP</th>
                            <th>Progress (Pending/Total)</th>
                            <th>Assigned</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if (empty($assignments)): ?>
                        <tr><td colspan="8" class="text-center text-muted py-4"><i class="bi bi-inbox"></i> No active assignments found</td></tr>
                    <?php endif; ?>

                    <?php foreach ($assignments as $a): ?>
                        <tr>
                            <td><span class="badge bg-success"><i class="bi bi-check-circle"></i> ACTIVE</span></td>
                            <td><?= htmlspecialchars($a['district_name'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($a['block_name']) ?></td>
                            <td>
                                <strong><?= htmlspecialchars($a['gp_name']) ?></strong><br>
                                <small class="text-muted"><?= htmlspecialchars($a['gp_id']) ?></small>
                            </td>
                            <td>
                                <?= htmlspecialchars($a['rep_name']) ?><br>
                                <small class="text-muted"><?= htmlspecialchars($a['rep_email']) ?></small>
                            </td>
                            <td>
                                <?php 
                                $total = $a['total_schools'] ?: 0;
                                $pending = $a['pending_schools'] ?: 0;
                                $percentage = $total > 0 ? round((($total - $pending)/$total)*100) : 0;
                                ?>
                                <div class="d-flex align-items-center gap-2">
                                    <span class="<?= $pending > 0 ? 'text-warning fw-bold' : 'text-success' ?>">
                                        <?= $pending ?>/<?= $total ?>
                                    </span>
                                    <div class="progress" style="width: 80px; height: 6px;">
                                        <div class="progress-bar bg-success" style="width: <?= $percentage ?>%"></div>
                                    </div>
                                    <small><?= $percentage ?>% complete</small>
                                </div>
                                <?php if ($pending == 0): ?>
                                    <small class="text-success"><i class="bi bi-check-circle"></i> All schools visited</small>
                                <?php endif; ?>
                            </td>
                            <td><?= date('d/m/Y', strtotime($a['assigned_on'])) ?></td>
                            <td>
                                <form method="post" class="d-inline" onsubmit="return confirmDeactivation()">
                                    <input type="hidden" name="csrf" value="<?= htmlspecialchars(csrf_token()) ?>">
                                    <input type="hidden" name="action" value="toggle_status">
                                    <input type="hidden" name="assign_id" value="<?= (int)$a['id'] ?>">
                                    <button type="submit" class="btn btn-sm btn-outline-danger" title="Deactivate">
                                        <i class="bi bi-pause-circle"></i>
                                    </button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Transfer History -->
        <?php if (!empty($transfers)): ?>
        <div class="card card-soft shadow-soft p-3 p-md-4">
            <h6 class="mb-3">
                <i class="bi bi-clock-history text-info"></i> Recent Transfer History
                <small class="text-muted">(Pending schools transferred to new REP)</small>
            </h6>
            
            <div class="table-responsive">
                <table class="table table-sm table-striped">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>GP</th>
                            <th>From REP</th>
                            <th>To REP</th>
                            <th>Total Schools</th>
                            <th>Visited (kept with previous REP)</th>
                            <th>Pending (transferred)</th>
                            <th>Reason</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($transfers as $t): ?>
                        <tr>
                            <td><?= date('d/m/Y H:i', strtotime($t['transfer_date'])) ?></td>
                            <td><?= htmlspecialchars($t['gp_name']) ?></td>
                            <td><?= htmlspecialchars($t['from_rep_name']) ?></td>
                            <td>
                                <?= htmlspecialchars($t['to_rep_name']) ?><br>
                                <small><?= htmlspecialchars($t['to_rep_email']) ?></small>
                            </td>
                            <td><?= $t['total_schools'] ?></td>
                            <td class="text-success"><?= $t['visited_schools'] ?> <small>(previous REP)</small></td>
                            <td class="text-warning fw-bold"><?= $t['pending_schools'] ?> <small>(transferred)</small></td>
                            <td><?= htmlspecialchars($t['reason']) ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <script>
    // Load assigned GPs
    let assignedGpIds = new Set();

    async function loadJSON(url) {
        try {
            const res = await fetch(url, {credentials: 'same-origin'});
            return res.ok ? await res.json() : [];
        } catch(e) {
            console.error('Fetch error:', e);
            return [];
        }
    }

    // Load assigned GPs on page load
    loadJSON('/school-crm/api/assigned_gps.php').then(data => {
        assignedGpIds = new Set(data.map(g => g.id));
    });

    // Transfer Form - GP selection
    const gpSelect = document.getElementById('gpSelect');
    if (gpSelect) {
        gpSelect.addEventListener('change', function() {
            const opt = this.options[this.selectedIndex];
            
            if (this.value) {
                const total = parseInt(opt.dataset.total || 0);
                const visited = parseInt(opt.dataset.visited || 0);
                const pending = parseInt(opt.dataset.pending || 0);
                
                document.getElementById('gpStats').style.display = 'block';
                document.getElementById('currentRepName').textContent = opt.dataset.repName;
                document.getElementById('gpLocation').textContent = opt.dataset.district + ' - ' + opt.dataset.block;
                document.getElementById('totalSchools').textContent = total;
                document.getElementById('visitedSchools').textContent = visited;
                document.getElementById('pendingSchools').textContent = pending;
                document.getElementById('pendingCount').textContent = pending;
                document.getElementById('fromRepId').value = opt.dataset.repId;
                
                if (pending > 0) {
                    document.getElementById('transferWarning').style.display = 'block';
                    document.getElementById('warningMessage').innerHTML = 
                        `<strong>⚠️ ${pending} schools pending!</strong> These will be transferred to the new REP.`;
                } else {
                    document.getElementById('transferWarning').style.display = 'none';
                }
            } else {
                document.getElementById('gpStats').style.display = 'none';
                document.getElementById('transferWarning').style.display = 'none';
            }
        });
    }

    // Confirm transfer
    function confirmTransfer() {
        const gp = document.getElementById('gpSelect');
        const toRep = document.getElementById('toRepSelect');
        const pending = parseInt(document.getElementById('pendingSchools')?.textContent || '0');
        const currentRep = document.getElementById('currentRepName')?.textContent || 'Unknown';
        
        if (!gp.value || !toRep.value) {
            alert('⚠️ Please select both GP and new REP');
            return false;
        }
        
        const message = pending > 0 
            ? `⚠️ WARNING: ${pending} schools are pending!\n\nThese ${pending} unvisited schools will be transferred to the new REP.\nVisited schools (${parseInt(document.getElementById('visitedSchools')?.textContent || '0')}) will remain with ${currentRep}'s history.\n\nAre you sure you want to transfer?`
            : `Transfer this GP from ${currentRep} to new REP?\n\nAll schools have been visited, so no pending schools to transfer.`;
        
        return confirm(message);
    }

    // Deactivation confirmation
    function confirmDeactivation() {
        return confirm('⚠️ Deactivate this assignment?\n\nThe GP will become available for reassignment.\nAll visit history will be preserved.');
    }

    // Bulk Assign - Dynamic selects
    const districtSel = document.getElementById('districtSel');
    const blockSel = document.getElementById('blockSel');
    const gpMultiSel = document.getElementById('gpSel');

    function setOptions(select, items, placeholder, disableAssigned = false) {
        select.innerHTML = '';
        
        if (placeholder) {
            const opt = document.createElement('option');
            opt.value = '';
            opt.textContent = placeholder;
            select.appendChild(opt);
        }
        
        items.forEach(item => {
            const opt = document.createElement('option');
            opt.value = item.id;
            opt.textContent = item.name + ' (' + item.id + ')';
            
            if (disableAssigned && assignedGpIds.has(item.id)) {
                opt.disabled = true;
                opt.textContent += ' (Already Assigned)';
            }
            
            select.appendChild(opt);
        });
    }

    if (districtSel) {
        districtSel.addEventListener('change', async function() {
            blockSel.disabled = true;
            gpMultiSel.disabled = true;
            gpMultiSel.innerHTML = '';
            
            if (this.value) {
                const blocks = await loadJSON('/school-crm/api/blocks.php?district_id=' + this.value);
                setOptions(blockSel, blocks, '-- Select Block --');
                blockSel.disabled = false;
            }
        });
    }

    if (blockSel) {
        blockSel.addEventListener('change', async function() {
            gpMultiSel.disabled = true;
            gpMultiSel.innerHTML = '';
            
            if (this.value) {
                const gps = await loadJSON('/school-crm/api/gps.php?block_id=' + this.value);
                setOptions(gpMultiSel, gps, null, true);
                gpMultiSel.size = Math.min(10, gps.length);
                gpMultiSel.disabled = false;
            }
        });
    }

    // Filter District change
    document.getElementById('filterDistrict')?.addEventListener('change', function() {
        const url = new URL(window.location.href);
        if (this.value) url.searchParams.set('district_id', this.value);
        else url.searchParams.delete('district_id');
        url.searchParams.delete('block_id');
        window.location.href = url;
    });

    // Validate bulk assign
    document.getElementById('assignForm')?.addEventListener('submit', function(e) {
        const selected = Array.from(gpMultiSel.selectedOptions);
        if (selected.some(opt => opt.disabled)) {
            e.preventDefault();
            alert('Cannot assign already assigned GPs');
        }
    });
    </script>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

<?php require_once __DIR__ . "/../partials/footer.php"; ?>