<?php
declare(strict_types=1);
ini_set('display_errors',1); error_reporting(E_ALL);
require_once __DIR__ . '/../includes/auth.php';
$db = ec_db(); if (!$db) die('DB error');
if (function_exists('require_role')) { require_role(['super_admin','admin']); } // stricter here

function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); }

$msg=''; $err='';
try{
  if (($_POST['action'] ?? '') === 'create') {
    $name = trim($_POST['name'] ?? ''); if ($name==='') throw new Exception('Name required.');
    $st = $db->prepare("INSERT INTO branches (name) VALUES (?)"); $st->bind_param('s',$name); $st->execute(); $st->close();
    $msg = "Branch added.";
  }
  if (($_POST['action'] ?? '') === 'rename') {
    $id = (int)($_POST['id'] ?? 0); $name = trim($_POST['name'] ?? ''); if ($name==='') throw new Exception('Name required.');
    $st = $db->prepare("UPDATE branches SET name=? WHERE id=?"); $st->bind_param('si',$name,$id); $st->execute(); $st->close();
    $msg = "Branch renamed.";
  }
  if (($_POST['action'] ?? '') === 'delete') {
    $id = (int)($_POST['id'] ?? 0);
    $count = 0;
    $st = $db->prepare("SELECT COUNT(*) FROM batches WHERE branch_id=?"); $st->bind_param('i',$id); $st->execute(); $st->bind_result($c1); $st->fetch(); $st->close(); $count += (int)$c1;
    $st = $db->prepare("SELECT COUNT(*) FROM leads WHERE branch_id=?");   $st->bind_param('i',$id); $st->execute(); $st->bind_result($c2); $st->fetch(); $st->close(); $count += (int)$c2;
    if ($count>0) throw new Exception("Cannot delete: referenced by {$count} records.");
    $db->prepare("DELETE FROM branches WHERE id=?")->bind_param('i',$id)->execute();
    $msg = "Branch deleted.";
  }
} catch(Throwable $e){ $err=$e->getMessage(); }

$rows=[]; $res=$db->query("SELECT id,name FROM branches ORDER BY name"); while($r=$res->fetch_assoc()) $rows[]=$r;

/* CSV export */
if (isset($_GET['export']) && $_GET['export'] === '1') {
  header('Content-Type: text/csv; charset=utf-8');
  header('Content-Disposition: attachment; filename="branches.csv"');
  $f = fopen('php://output', 'w'); fputcsv($f, ['ID','Name']); foreach ($rows as $r) fputcsv($f, [$r['id'], $r['name']]); exit;
}
?>
<!doctype html><html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Branch Manager</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
  <?php
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';

$canViewIncome = ec_can('reports.view');
$canViewDues   = ec_can('payments.manage');

?>
<main class="ec-main">
<body class="bg-light">
    
<div class="container py-3">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h4 class="mb-0">Branch Manager</h4>
    <div class="d-flex gap-2">
      <a class="btn btn-outline-secondary btn-sm" href="?export=1">Export CSV</a>
      <a class="btn btn-outline-primary btn-sm" href="dashboard.php">Back</a>
    </div>
  </div>
  <?php if($msg): ?><div class="alert alert-success py-2"><?=esc($msg)?></div><?php endif; ?>
  <?php if($err): ?><div class="alert alert-danger py-2"><?=esc($err)?></div><?php endif; ?>

  <div class="card border-0 shadow-sm mb-3"><div class="card-body">
    <h6 class="fw-bold mb-3">Add Branch</h6>
    <form method="post" class="row g-2">
      <input type="hidden" name="action" value="create">
      <div class="col-md-6"><input class="form-control" name="name" placeholder="Branch name" required></div>
      <div class="col-md-2"><button class="btn btn-primary">Add</button></div>
    </form>
  </div></div>

  <div class="card border-0 shadow-sm"><div class="card-body">
    <div class="table-responsive">
      <table class="table table-sm align-middle">
        <thead class="table-light"><tr><th style="width:60%">Name</th><th class="text-end">Actions</th></tr></thead>
        <tbody>
          <?php foreach($rows as $r): ?>
          <tr>
            <td>
              <form method="post" class="d-flex gap-2">
                <input type="hidden" name="action" value="rename">
                <input type="hidden" name="id" value="<?=$r['id']?>">
                <input class="form-control form-control-sm" name="name" value="<?=esc($r['name'])?>">
                <button class="btn btn-sm btn-outline-success">Save</button>
              </form>
            </td>
            <td class="text-end">
              <form method="post" class="d-inline" onsubmit="return confirm('Delete this branch? This will fail if referenced by batches/leads.');">
                <input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?=$r['id']?>">
                <button class="btn btn-sm btn-outline-danger">Delete</button>
              </form>
            </td>
          </tr>
          <?php endforeach; if(!$rows): ?>
          <tr><td colspan="2" class="text-center text-muted">No branches yet.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
    <div class="small text-muted">Deleting is blocked if any <b>batches</b> or <b>leads</b> reference the branch.</div>
  </div></div>
</div>
</main>
</body></html>
