<?php
session_start();
$active_nav = 'organization_view';
include_once("config/db.php");
require_once __DIR__ . '/header.php';

// CSRF helpers (same inline pattern)
if (!function_exists('csrf_token')) {
    function csrf_token(): string {
        if (empty($_SESSION['csrf_token'])) $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        return $_SESSION['csrf_token'];
    }
    function csrf_verify(): bool {
        return !empty($_POST['csrf_token']) && !empty($_SESSION['csrf_token'])
            && hash_equals($_SESSION['csrf_token'], $_POST['csrf_token']);
    }
    function csrf_field(): string { return '<input type="hidden" name="csrf_token" value="'.htmlspecialchars(csrf_token()).'">'; }
}
// Previously trapped inside the csrf_token fallback above — guard individually
// so they exist even when includes/csrf.php provides the csrf helpers.
if (!function_exists('csrf_verify')) {
    function csrf_verify(): bool {
        return !empty($_POST['csrf_token']) && !empty($_SESSION['csrf_token'])
            && hash_equals($_SESSION['csrf_token'], $_POST['csrf_token']);
    }
}
if (!function_exists('h')) {
    function h(?string $v): string { return htmlspecialchars($v ?? '', ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); }
}

$org_id = (int)($_GET['id'] ?? 0);
if (!$org_id) { header("Location: organizations.php"); exit; }

// Load org
$org_stmt = $conn->prepare(
    "SELECT o.*, u.name AS creator_name FROM organizations o
     LEFT JOIN users u ON o.created_by=u.id
     WHERE o.id=? LIMIT 1"
);
$org_stmt->bind_param("i", $org_id);
$org_stmt->execute();
$org = $org_stmt->get_result()->fetch_assoc();
if (!$org) { header("Location: organizations.php"); exit; }

$page_title = h($org['name']);

$success = '';
$error   = '';

// ─── Handle status toggle via POST ─────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) { $error = "Security token mismatch."; goto render; }

    $form_action = $_POST['form_action'] ?? '';

    if ($form_action === 'set_status') {
        $new_status = $_POST['new_status'] ?? '';
        if (!in_array($new_status, ['active','suspended','inactive'])) { $error = "Invalid status."; goto render; }
        $upd = $conn->prepare("UPDATE organizations SET status=? WHERE id=?");
        $upd->bind_param("si", $new_status, $org_id);
        $upd->execute();
        $org['status'] = $new_status;

        // If suspending, also force-logout all org_admin sessions (mark users as suspended)
        if ($new_status === 'suspended') {
            $conn->query("UPDATE users SET status=0 WHERE organization_id={$org_id} AND role='org_admin'");
        } elseif ($new_status === 'active') {
            $conn->query("UPDATE users SET status=1 WHERE organization_id={$org_id} AND role='org_admin'");
        }
        $success = "Organisation status updated to <strong>" . ucfirst($new_status) . "</strong>.";
    }

    // Create org_admin (add additional admin)
    if ($form_action === 'add_admin') {
        $admin_name     = trim($_POST['admin_name']     ?? '');
        $admin_email    = trim($_POST['admin_email']    ?? '');
        $admin_password = trim($_POST['admin_password'] ?? '');

        if (!$admin_name || !$admin_email || !$admin_password) { $error = "All fields are required."; goto render; }
        if (strlen($admin_password) < 8) { $error = "Password must be at least 8 characters."; goto render; }

        $chk = $conn->prepare("SELECT id FROM users WHERE email=? LIMIT 1");
        $chk->bind_param("s", $admin_email); $chk->execute();
        if ($chk->get_result()->num_rows > 0) { $error = "Email already exists."; goto render; }

        $hash = password_hash($admin_password, PASSWORD_BCRYPT);
        $ins  = $conn->prepare("INSERT INTO users (name,email,password,role,organization_id,status,created_at) VALUES (?,?,?,'org_admin',?,1,NOW())");
        $ins->bind_param("sssi", $admin_name, $admin_email, $hash, $org_id);
        $ins->execute() ? $success = "Administrator added." : $error = "Failed to add administrator.";
    }
}

render:

// Stats
$stats_stmt = $conn->prepare(
    "SELECT
       COUNT(CASE WHEN role='org_staff' AND status=1 THEN 1 END) AS active_staff,
       COUNT(CASE WHEN role='org_staff' AND status=0 THEN 1 END) AS suspended_staff,
       COUNT(CASE WHEN role='org_admin' THEN 1 END) AS admins
     FROM users WHERE organization_id=?"
);
$stats_stmt->bind_param("i", $org_id); $stats_stmt->execute();
$stats = $stats_stmt->get_result()->fetch_assoc();

// Wallet total
$wt = $conn->prepare(
    "SELECT COALESCE(SUM(w.balance),0) FROM wallets w
     INNER JOIN users u ON w.user_id=u.id
     WHERE u.organization_id=? AND w.wallet_type='meal_ticket'"
);
$wt->bind_param("i", $org_id); $wt->execute();
$mt_total = (float)$wt->get_result()->fetch_row()[0];

// Total funded
$tf = $conn->prepare(
    "SELECT COALESCE(SUM(total_amount),0), COUNT(*) FROM org_funding_batches WHERE organization_id=? AND status='completed'"
);
$tf->bind_param("i", $org_id); $tf->execute();
[$total_funded, $total_batches] = $tf->get_result()->fetch_row();

// Admins list
$admins = $conn->prepare("SELECT id,name,email,status,created_at FROM users WHERE organization_id=? AND role='org_admin' ORDER BY created_at ASC");
$admins->bind_param("i", $org_id); $admins->execute();
$admin_list = $admins->get_result()->fetch_all(MYSQLI_ASSOC);

// Recent staff
$staff_stmt = $conn->prepare(
    "SELECT u.id,u.name,u.email,u.employee_id,u.department,u.status,COALESCE(w.balance,0) AS mt_balance
     FROM users u
     LEFT JOIN wallets w ON w.user_id=u.id AND w.wallet_type='meal_ticket'
     WHERE u.organization_id=? AND u.role='org_staff'
     ORDER BY u.created_at DESC LIMIT 10"
);
$staff_stmt->bind_param("i", $org_id); $staff_stmt->execute();
$staff_list = $staff_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Recent batches
$batches_stmt = $conn->prepare(
    "SELECT b.*, u.name AS admin_name FROM org_funding_batches b
     INNER JOIN users u ON b.funded_by=u.id
     WHERE b.organization_id=? ORDER BY b.created_at DESC LIMIT 5"
);
$batches_stmt->bind_param("i", $org_id); $batches_stmt->execute();
$batches = $batches_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
?>

<div class="anim-up">

<!-- Breadcrumb -->
<div style="font-size:.8rem;color:var(--text-muted);margin-bottom:20px">
  <a href="organizations.php" style="color:var(--primary);font-weight:600">Organisations</a>
  <span style="margin:0 8px">›</span>
  <span><?php echo h($org['name']); ?></span>
</div>

<!-- Org header -->
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:24px;gap:12px;flex-wrap:wrap">
  <div style="display:flex;align-items:center;gap:16px">
    <div style="width:56px;height:56px;border-radius:16px;background:var(--primary-bg);display:flex;align-items:center;justify-content:center;flex-shrink:0">
      <svg width="26" height="26" viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="var(--primary)" stroke-linecap="round"><path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>
    </div>
    <div>
      <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
        <h2 style="font-size:1.35rem;font-weight:800;letter-spacing:-.03em"><?php echo h($org['name']); ?></h2>
        <?php
        $sc = match($org['status']) { 'active'=>'badge-success','suspended'=>'badge-error',default=>'badge-muted' };
        echo '<span class="badge '.$sc.'">'.ucfirst($org['status']).'</span>';
        ?>
        <span class="badge badge-info"><?php echo ucfirst($org['type']); ?></span>
      </div>
      <?php if ($org['email']): ?>
      <p style="font-size:.84rem;color:var(--text-muted);margin-top:3px"><?php echo h($org['email']); ?><?php if($org['phone']): ?> · <?php echo h($org['phone']); ?><?php endif; ?></p>
      <?php endif; ?>
    </div>
  </div>
  <div style="display:flex;gap:8px">
    <a href="organization_edit.php?id=<?php echo $org_id; ?>" class="btn btn-secondary btn-md">Edit Details</a>
    <?php if ($org['status'] === 'active'): ?>
    <button onclick="openModal('suspendModal')" class="btn btn-danger btn-md">Suspend</button>
    <?php elseif ($org['status'] === 'suspended'): ?>
    <button onclick="openModal('activateModal')" class="btn btn-success btn-md">Activate</button>
    <?php endif; ?>
  </div>
</div>

<?php if ($success): ?>
<div class="alert alert-success"><svg viewBox="0 0 24 24" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg><?php echo $success; ?></div>
<?php endif; ?>
<?php if ($error): ?>
<div class="alert alert-error"><svg viewBox="0 0 24 24" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg><?php echo $error; ?></div>
<?php endif; ?>

<!-- Stats -->
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:14px;margin-bottom:24px">
  <div class="stat-card" style="border-top:3px solid var(--primary)">
    <div class="stat-label">Active Staff</div>
    <div class="stat-value" style="color:var(--primary)"><?php echo $stats['active_staff']; ?></div>
    <?php if ($stats['suspended_staff']): ?><div class="stat-sub" style="color:var(--error)"><?php echo $stats['suspended_staff']; ?> suspended</div><?php else: ?><div class="stat-sub">All active</div><?php endif; ?>
  </div>
  <div class="stat-card" style="border-top:3px solid #7C3AED">
    <div class="stat-label">MT Balance</div>
    <div class="stat-value" style="font-size:1.2rem;color:#7C3AED">₦<?php echo number_format($mt_total,2); ?></div>
    <div class="stat-sub">In circulation</div>
  </div>
  <div class="stat-card" style="border-top:3px solid var(--success)">
    <div class="stat-label">Total Funded</div>
    <div class="stat-value" style="font-size:1.2rem;color:var(--success)">₦<?php echo number_format($total_funded,2); ?></div>
    <div class="stat-sub"><?php echo $total_batches; ?> batch<?php echo $total_batches!=1?'es':''; ?></div>
  </div>
  <div class="stat-card" style="border-top:3px solid var(--warning)">
    <div class="stat-label">Administrators</div>
    <div class="stat-value" style="color:var(--warning)"><?php echo $stats['admins']; ?></div>
    <div class="stat-sub">Org admin accounts</div>
  </div>
</div>

<div style="display:grid;grid-template-columns:1fr 320px;gap:20px;align-items:start">

  <div style="display:flex;flex-direction:column;gap:16px">

    <!-- Recent staff -->
    <div class="card">
      <div class="card-header">
        <h3>Staff Members (<?php echo $stats['active_staff'] + $stats['suspended_staff']; ?>)</h3>
      </div>
      <?php if (empty($staff_list)): ?>
      <div class="card-body" style="font-size:.84rem;color:var(--text-muted);text-align:center">No staff members yet.</div>
      <?php else: ?>
      <div style="overflow-x:auto">
        <table class="data-table">
          <thead><tr><th>Name</th><th>Employee ID</th><th>Department</th><th>MT Balance</th><th>Status</th></tr></thead>
          <tbody>
            <?php foreach ($staff_list as $s): ?>
            <tr>
              <td>
                <div style="font-weight:600;font-size:.84rem"><?php echo h($s['name']); ?></div>
                <div style="font-size:.72rem;color:var(--text-muted)"><?php echo h($s['email']); ?></div>
              </td>
              <td style="font-family:monospace;font-size:.78rem"><?php echo h($s['employee_id'] ?: '—'); ?></td>
              <td style="font-size:.8rem"><?php echo h($s['department'] ?: '—'); ?></td>
              <td style="font-weight:700;color:var(--success);font-size:.82rem">₦<?php echo number_format($s['mt_balance'],2); ?></td>
              <td><?php echo $s['status'] ? '<span class="badge badge-success">Active</span>' : '<span class="badge badge-error">Suspended</span>'; ?></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
      <?php endif; ?>
    </div>

    <!-- Recent funding -->
    <?php if (!empty($batches)): ?>
    <div class="card">
      <div class="card-header"><h3>Recent Funding Batches</h3></div>
      <div style="overflow-x:auto">
        <table class="data-table">
          <thead><tr><th>Date</th><th>Type</th><th>Staff</th><th>Total</th><th>Status</th></tr></thead>
          <tbody>
            <?php foreach ($batches as $b): ?>
            <tr>
              <td style="font-size:.78rem;color:var(--text-muted)"><?php echo date('M j, Y', strtotime($b['created_at'])); ?></td>
              <td><span class="badge badge-primary"><?php echo ucfirst(str_replace('_',' ',$b['batch_type'])); ?></span></td>
              <td><?php echo $b['staff_count']; ?></td>
              <td style="font-weight:700">₦<?php echo number_format($b['total_amount'],2); ?></td>
              <td><?php
                $bc = match($b['status']) {'completed'=>'badge-success','failed'=>'badge-error',default=>'badge-warning'};
                echo '<span class="badge '.$bc.'">'.ucfirst($b['status']).'</span>';
              ?></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
    <?php endif; ?>

  </div>

  <!-- Right column -->
  <div style="display:flex;flex-direction:column;gap:14px">

    <!-- Org info -->
    <div class="card card-body" style="padding:18px 20px">
      <h3 style="font-size:.88rem;font-weight:700;margin-bottom:14px">Organisation Info</h3>
      <?php
      $info_fields = [
        'Contact Person' => $org['contact_person'],
        'Email'          => $org['email'],
        'Phone'          => $org['phone'],
        'Address'        => $org['address'],
        'Created By'     => $org['creator_name'],
        'Created'        => $org['created_at'] ? date('M j, Y', strtotime($org['created_at'])) : '—',
      ];
      foreach ($info_fields as $label => $val):
        if (!$val) continue;
      ?>
      <div style="margin-bottom:10px">
        <div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.1em;color:var(--text-muted)"><?php echo $label; ?></div>
        <div style="font-size:.84rem;font-weight:600;margin-top:2px"><?php echo h($val); ?></div>
      </div>
      <?php endforeach; ?>
    </div>

    <!-- Administrators -->
    <div class="card card-body" style="padding:18px 20px">
      <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:12px">
        <h3 style="font-size:.88rem;font-weight:700">Administrators</h3>
        <button onclick="openModal('addAdminModal')" class="btn btn-secondary btn-sm">+ Add</button>
      </div>
      <?php foreach ($admin_list as $adm): ?>
      <div style="display:flex;align-items:center;gap:10px;padding:8px 0;border-bottom:1px solid var(--border)">
        <div style="width:32px;height:32px;border-radius:50%;background:var(--primary-bg);display:flex;align-items:center;justify-content:center;font-size:.72rem;font-weight:800;color:var(--primary);flex-shrink:0">
          <?php echo strtoupper(substr($adm['name'],0,1)); ?>
        </div>
        <div style="flex:1;overflow:hidden">
          <div style="font-size:.84rem;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><?php echo h($adm['name']); ?></div>
          <div style="font-size:.72rem;color:var(--text-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><?php echo h($adm['email']); ?></div>
        </div>
        <?php echo $adm['status'] ? '<span class="badge badge-success" style="font-size:.6rem">Active</span>' : '<span class="badge badge-error" style="font-size:.6rem">Off</span>'; ?>
      </div>
      <?php endforeach; ?>
    </div>

  </div>
</div>

</div>

<!-- Suspend Modal -->
<div class="modal-backdrop" id="suspendModal">
  <div class="modal">
    <div class="modal-header"><h3 style="color:var(--error)">Suspend Organisation</h3>
      <button class="modal-close" onclick="closeModal('suspendModal')"><svg viewBox="0 0 24 24" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
    </div>
    <form method="POST">
      <?php echo csrf_field(); ?>
      <input type="hidden" name="form_action" value="set_status">
      <input type="hidden" name="new_status" value="suspended">
      <div class="modal-body">
        <p>Suspending <strong><?php echo h($org['name']); ?></strong> will immediately lock out all organisation administrators. Staff wallets remain intact.</p>
        <div class="alert alert-warning" style="margin-top:14px">
          <svg viewBox="0 0 24 24" stroke-width="2"><path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
          This action will immediately log out all org admins.
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-md" onclick="closeModal('suspendModal')">Cancel</button>
        <button type="submit" class="btn btn-danger btn-md">Confirm Suspend</button>
      </div>
    </form>
  </div>
</div>

<!-- Activate Modal -->
<div class="modal-backdrop" id="activateModal">
  <div class="modal">
    <div class="modal-header"><h3 style="color:var(--success)">Activate Organisation</h3>
      <button class="modal-close" onclick="closeModal('activateModal')"><svg viewBox="0 0 24 24" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
    </div>
    <form method="POST">
      <?php echo csrf_field(); ?>
      <input type="hidden" name="form_action" value="set_status">
      <input type="hidden" name="new_status" value="active">
      <div class="modal-body">
        <p>Activate <strong><?php echo h($org['name']); ?></strong>? Organisation administrators will regain portal access.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-md" onclick="closeModal('activateModal')">Cancel</button>
        <button type="submit" class="btn btn-success btn-md">Confirm Activate</button>
      </div>
    </form>
  </div>
</div>

<!-- Add Admin Modal -->
<div class="modal-backdrop" id="addAdminModal">
  <div class="modal">
    <div class="modal-header"><h3>Add Administrator</h3>
      <button class="modal-close" onclick="closeModal('addAdminModal')"><svg viewBox="0 0 24 24" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
    </div>
    <form method="POST">
      <?php echo csrf_field(); ?>
      <input type="hidden" name="form_action" value="add_admin">
      <div class="modal-body">
        <div class="form-group"><label>Full Name *</label><input type="text" name="admin_name" class="form-control" required></div>
        <div class="form-group"><label>Email *</label><input type="email" name="admin_email" class="form-control" required></div>
        <div class="form-group"><label>Password *</label><input type="password" name="admin_password" class="form-control" minlength="8" required></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-md" onclick="closeModal('addAdminModal')">Cancel</button>
        <button type="submit" class="btn btn-primary btn-md">Add Administrator</button>
      </div>
    </form>
  </div>
</div>

<style>
.stat-card{background:var(--white);border:1px solid var(--border);border-radius:var(--radius-lg);padding:18px 20px}
.stat-card .stat-label{font-size:.72rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:6px}
.stat-card .stat-value{font-size:1.6rem;font-weight:800;letter-spacing:-.03em;line-height:1}
.stat-card .stat-sub{font-size:.75rem;color:var(--text-muted);margin-top:4px}
</style>

<?php include_once("footer.php"); ?>
