<?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);
}

/**
 * 1) Create assignments (bulk)
 * Admin selects: rep + block + multiple gp_ids
 */
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.");
                }

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

                // If a GP is already ACTIVE for another rep, we will make it INACTIVE first (optional)
                // Here we do safer approach: if already ACTIVE somewhere, we deactivate old and assign new.
                $stDeactivateOld = $pdo->prepare("UPDATE gp_assignments SET status='INACTIVE' WHERE gp_id=? AND status='ACTIVE'");

                // If exists record for same user+gp, just set ACTIVE
                $stUpsert = $pdo->prepare("
                    INSERT INTO gp_assignments (block_id, gp_id, user_id, status, assigned_on)
                    VALUES (?, ?, ?, 'ACTIVE', ?)
                    ON DUPLICATE KEY UPDATE
                      block_id = VALUES(block_id),
                      user_id = VALUES(user_id),
                      status  = 'ACTIVE',
                      assigned_on = VALUES(assigned_on)
                ");

                $today = date('Y-m-d');
                $assignedCount = 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()) {
                        continue; // skip invalid GP for this block
                    }

                    // deactivate old active assignment (if any)
                    $stDeactivateOld->execute([$gp_id]);

                    // upsert new assignment as ACTIVE
                    $stUpsert->execute([$block_id, $gp_id, $user_id, $today]);
                    $assignedCount++;
                }

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

/**
 * 2) Toggle assignment status Active/Inactive
 */
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 {
            $st = $pdo->prepare("UPDATE gp_assignments SET status = IF(status='ACTIVE','INACTIVE','ACTIVE') WHERE id=?");
            $st->execute([$assign_id]);
            $success = "Assignment status updated.";
        }
    }
}

/**
 * Dropdown data
 */
$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");

/**
 * Filters (optional)
 */
$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 assignment list
 */
$where = "1=1";
$params = [];

if ($filter_district !== '') {
    $where .= " AND b.district_id=?";
    $params[] = $filter_district;
}
if ($filter_block !== '') {
    $where .= " AND a.block_id=?";
    $params[] = $filter_block;
}

$assignments = fetchAll($pdo, "
    SELECT
      a.id, a.status, a.assigned_on,
      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.name AS district_name
    FROM gp_assignments a
    JOIN users u ON u.id=a.user_id
    JOIN gps g ON g.id=a.gp_id
    JOIN blocks b ON b.id=a.block_id
    LEFT JOIN districts d ON d.id=b.district_id
    WHERE {$where}
    ORDER BY a.status='ACTIVE' DESC, d.name ASC, b.name ASC, u.name ASC, g.name ASC
", $params);

/**
 * For the assign form: Blocks list based on selected district (via JS fetch /api/blocks.php)
 * For the assign form: GPs list based on selected block (via JS fetch /api/gps.php)
 */

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

<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">GP Assignments</h5>
    <div class="text-muted small">Assign multiple GPs to a Rep (2–3 reps per block)</div>
  </div>
  <div class="d-flex gap-2">
    <a class="btn btn-outline-dark btn-sm" href="/school-crm/public/admin/users.php">Users</a>
    <a class="btn btn-outline-dark btn-sm" href="/school-crm/public/admin/districts.php">Districts</a>
  </div>
</div>

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

<!-- Assign form -->
<div class="card card-soft shadow-soft p-3 p-md-4 mb-3">
  <h6 class="mb-3">Assign 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">Rep <span class="text-danger">*</span></label>
      <select class="form-select" name="user_id" required>
        <option value="">Select 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">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']) ?> (<?= htmlspecialchars($d['id']) ?>)</option>
        <?php endforeach; ?>
      </select>
      <div class="form-text">District dropdown is for loading Blocks.</div>
    </div>

    <div class="col-12 col-md-4">
      <label class="form-label">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 class="form-text">Select block to load GPs.</div>
    </div>

    <div class="col-12">
      <label class="form-label">Select GPs (Multiple) <span class="text-danger">*</span></label>
      <select class="form-select" name="gp_ids[]" id="gpSel" multiple size="10" disabled required></select>
      <div class="form-text">
        Tip: Ctrl/Shift ধরে multiple GP select করতে পারো (Mobile এ tap করে multiple select হবে)।
      </div>
    </div>

    <div class="col-12 d-grid d-md-flex justify-content-md-end">
      <button class="btn btn-dark px-4">Assign Selected GPs</button>
    </div>
  </form>
</div>

<!-- Filters + List -->
<div class="card card-soft shadow-soft p-3 p-md-4">
  <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-2 mb-3">
    <h6 class="mb-0">Assignments List</h6>

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

      <select class="form-select form-select-sm" name="block_id" id="filterBlock" style="min-width:220px;" <?= ($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']) ?> (<?= htmlspecialchars($b['id']) ?>)
          </option>
        <?php endforeach; ?>
      </select>

      <button class="btn btn-sm btn-outline-dark">Filter</button>
    </form>
  </div>

  <div class="table-responsive">
    <table class="table table-striped align-middle mb-0">
      <thead>
        <tr>
          <th>Status</th>
          <th>District</th>
          <th>Block</th>
          <th>GP</th>
          <th>Rep</th>
          <th class="text-nowrap">Assigned On</th>
          <th class="text-end">Action</th>
        </tr>
      </thead>
      <tbody>
      <?php if (!$assignments): ?>
        <tr><td colspan="7" class="text-muted">No assignments found.</td></tr>
      <?php endif; ?>

      <?php foreach ($assignments as $a): ?>
        <tr>
          <td>
            <?php if (($a['status'] ?? '') === 'ACTIVE'): ?>
              <span class="badge bg-success">ACTIVE</span>
            <?php else: ?>
              <span class="badge bg-secondary">INACTIVE</span>
            <?php endif; ?>
          </td>
          <td><?= htmlspecialchars($a['district_name'] ?? '-') ?></td>
          <td><?= htmlspecialchars($a['block_name']) ?> (<?= htmlspecialchars($a['block_id']) ?>)</td>
          <td><?= htmlspecialchars($a['gp_name']) ?> (<?= htmlspecialchars($a['gp_id']) ?>)</td>
          <td><?= htmlspecialchars($a['rep_name']) ?> <span class="text-muted small">(<?= htmlspecialchars($a['rep_email']) ?>)</span></td>
          <td class="text-nowrap"><?= htmlspecialchars($a['assigned_on']) ?></td>
          <td class="text-end">
            <form method="post" class="d-inline">
              <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 class="btn btn-sm btn-outline-primary">Toggle</button>
            </form>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<script>
async function loadJSON(url){
  const res = await fetch(url, {credentials:'same-origin'});
  if(!res.ok) return [];
  return await res.json();
}

const districtSel = document.getElementById('districtSel');
const blockSel    = document.getElementById('blockSel');
const gpSel       = document.getElementById('gpSel');

function setOptions(selectEl, rows, placeholder){
  selectEl.innerHTML = '';
  if (placeholder !== null) {
    const o0 = document.createElement('option');
    o0.value = '';
    o0.textContent = placeholder;
    selectEl.appendChild(o0);
  }
  rows.forEach(r=>{
    const o = document.createElement('option');
    o.value = r.id;
    o.textContent = r.name + " (" + r.id + ")";
    selectEl.appendChild(o);
  });
}

function disableSelect(selectEl, placeholder){
  selectEl.disabled = true;
  setOptions(selectEl, [], placeholder);
}

// District -> Blocks
districtSel.addEventListener('change', async ()=>{
  disableSelect(blockSel, 'Select Block');
  gpSel.disabled = true;
  gpSel.innerHTML = '';

  const did = districtSel.value;
  if(!did) return;

  const blocks = await loadJSON('/school-crm/api/blocks.php?district_id=' + encodeURIComponent(did));
  setOptions(blockSel, blocks, 'Select Block');
  blockSel.disabled = false;
});

// Block -> GPs (multi)
blockSel.addEventListener('change', async ()=>{
  gpSel.disabled = true;
  gpSel.innerHTML = '';

  const bid = blockSel.value;
  if(!bid) return;

  const gps = await loadJSON('/school-crm/api/gps.php?block_id=' + encodeURIComponent(bid));
  // multi select: no placeholder
  setOptions(gpSel, gps, null);
  gpSel.size = Math.min(12, Math.max(6, gps.length));
  gpSel.disabled = false;
});

// Filter: district -> reload blocks options by reloading page (simple)
document.getElementById('filterDistrict').addEventListener('change', ()=>{
  const d = document.getElementById('filterDistrict').value;
  const url = new URL(window.location.href);
  if (d) url.searchParams.set('district_id', d);
  else url.searchParams.delete('district_id');
  url.searchParams.delete('block_id');
  window.location.href = url.toString();
});
</script>

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