<?php
session_start();
$page_title = 'Organisations';
$active_nav = 'organizations';
include_once("config/db.php");
require_once __DIR__ . '/organization/includes/org_heal.php';
dabil_org_heal($conn); // ensure org roles exist + repair blank-role accounts/wallets created before the fix
include_once("includes/csrf.php"); // fallback — define helpers inline if not present
require_once __DIR__ . '/header.php';

// ─── CSRF helpers (inline if not in a shared file) ─────────────────────
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()) . '">';
    }
}
// These were previously trapped inside the csrf_token fallback above, so they
// vanished as soon as includes/csrf.php existed. Guard them individually.
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'); }
}

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

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

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

    // ─── Create organisation ─────────────────────────────────────────────
    if ($form_action === 'create') {
        $name           = trim($_POST['name']           ?? '');
        $type           = trim($_POST['type']           ?? '');
        $contact_person = trim($_POST['contact_person'] ?? '');
        $email          = trim($_POST['email']          ?? '');
        $phone          = trim($_POST['phone']          ?? '');
        $address        = trim($_POST['address']        ?? '');
        $admin_name     = trim($_POST['admin_name']     ?? '');
        $admin_email    = trim($_POST['admin_email']    ?? '');
        $admin_password = trim($_POST['admin_password'] ?? '');

        if (!$name || !$type || !$admin_name || !$admin_email || !$admin_password) {
            $error = "Organisation name, type, and administrator details are required.";
            goto render;
        }
        if (!filter_var($admin_email, FILTER_VALIDATE_EMAIL)) {
            $error = "Invalid administrator email address.";
            goto render;
        }
        if (strlen($admin_password) < 8) {
            $error = "Admin password must be at least 8 characters.";
            goto render;
        }

        // Check admin email uniqueness
        $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 = "An account with the admin email already exists.";
            goto render;
        }

        $conn->begin_transaction();
        try {
            // Create organisation
            $ins_org = $conn->prepare(
                "INSERT INTO organizations (name, type, contact_person, email, phone, address, status, created_by, created_at)
                 VALUES (?, ?, ?, ?, ?, ?, 'active', ?, NOW())"
            );
            $ins_org->bind_param("ssssssi", $name, $type, $contact_person, $email, $phone, $address, $uid);
            $ins_org->execute();
            $new_org_id = $conn->insert_id;

            // Create org_admin user
            $hash    = password_hash($admin_password, PASSWORD_BCRYPT);
            $ins_adm = $conn->prepare(
                "INSERT INTO users (name, email, password, role, organization_id, status, created_at)
                 VALUES (?, ?, ?, 'org_admin', ?, 1, NOW())"
            );
            $ins_adm->bind_param("sssi", $admin_name, $admin_email, $hash, $new_org_id);
            $ins_adm->execute();

            $conn->commit();
            $success = "Organisation <strong>" . h($name) . "</strong> created with administrator account.";
        } catch (Exception $e) {
            $conn->rollback();
            $error = "Failed to create organisation: " . $e->getMessage();
        }
    }
}

render:

// ─── List organisations ──────────────────────────────────────────────────
$search     = trim($_GET['q']      ?? '');
$filter_status = $_GET['status'] ?? 'all';

$where_parts = ["1=1"];
$bind_types  = "";
$bind_vals   = [];

if ($search) {
    $where_parts[] = "(o.name LIKE ? OR o.email LIKE ? OR o.contact_person LIKE ?)";
    $bind_types   .= "sss";
    $like          = "%{$search}%";
    $bind_vals[]   = $like; $bind_vals[] = $like; $bind_vals[] = $like;
}

if ($filter_status !== 'all') {
    $where_parts[] = "o.status = ?";
    $bind_types   .= "s";
    $bind_vals[]   = $filter_status;
}

$where = implode(' AND ', $where_parts);

$sql = "SELECT o.*,
               u_creator.name AS created_by_name,
               COUNT(DISTINCT u_staff.id) AS staff_count,
               COUNT(DISTINCT u_admin.id) AS admin_count,
               COALESCE(SUM(w.balance),0) AS total_mt_balance
        FROM organizations o
        LEFT JOIN users u_creator ON o.created_by = u_creator.id
        LEFT JOIN users u_staff   ON u_staff.organization_id=o.id AND u_staff.role='org_staff' AND u_staff.status=1
        LEFT JOIN users u_admin   ON u_admin.organization_id=o.id AND u_admin.role='org_admin'
        LEFT JOIN wallets w ON w.organization_id=o.id AND w.wallet_type='meal_ticket'
        WHERE {$where}
        GROUP BY o.id
        ORDER BY o.created_at DESC";

if ($bind_types) {
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($bind_types, ...$bind_vals);
    $stmt->execute();
    $orgs = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
} else {
    $orgs = $conn->query($sql)->fetch_all(MYSQLI_ASSOC);
}

$total        = count($orgs);
$active_count = count(array_filter($orgs, fn($o) => $o['status'] === 'active'));
$suspended    = count(array_filter($orgs, fn($o) => $o['status'] === 'suspended'));
?>

<div class="anim-up">

<!-- Page header -->
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:24px;flex-wrap:wrap;gap:12px">
  <div>
    <h2 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em">Organisations</h2>
    <p style="font-size:.84rem;color:var(--text-muted);margin-top:3px"><?php echo $active_count; ?> active · <?php echo $suspended; ?> suspended</p>
  </div>
  <button onclick="openModal('createOrgModal')" class="btn btn-primary btn-md">
    <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
    Add Organisation
  </button>
</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; ?>

<!-- Filter -->
<div class="card card-body" style="padding:14px 18px;margin-bottom:16px">
  <form method="GET" style="display:flex;align-items:center;gap:12px;flex-wrap:wrap">
    <div style="flex:1;min-width:220px;position:relative">
      <svg style="position:absolute;left:12px;top:50%;transform:translateY(-50%);width:15px;height:15px;stroke:var(--text-light);fill:none" viewBox="0 0 24 24" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
      <input type="text" name="q" value="<?php echo h($search); ?>" placeholder="Search name, email, contact…" class="form-control" style="padding-left:38px">
    </div>
    <select name="status" class="form-control" style="width:auto;min-width:140px">
      <option value="all"       <?php echo $filter_status==='all'?'selected':''; ?>>All Status</option>
      <option value="active"    <?php echo $filter_status==='active'?'selected':''; ?>>Active</option>
      <option value="suspended" <?php echo $filter_status==='suspended'?'selected':''; ?>>Suspended</option>
      <option value="inactive"  <?php echo $filter_status==='inactive'?'selected':''; ?>>Inactive</option>
    </select>
    <button type="submit" class="btn btn-secondary btn-md">Filter</button>
    <?php if ($search || $filter_status!=='all'): ?>
    <a href="organizations.php" class="btn btn-secondary btn-md">Clear</a>
    <?php endif; ?>
    <span style="font-size:.82rem;color:var(--text-muted);margin-left:auto"><?php echo number_format($total); ?> result<?php echo $total!==1?'s':''; ?></span>
  </form>
</div>

<!-- Table -->
<div class="card">
  <?php if (empty($orgs)): ?>
  <div style="text-align:center;padding:56px 24px">
    <p style="font-weight:700;margin-bottom:6px"><?php echo $search ? 'No organisations found' : 'No organisations yet'; ?></p>
    <p style="font-size:.82rem;color:var(--text-muted);margin-bottom:16px"><?php echo $search ? 'Try a different search' : 'Create your first organisation to get started'; ?></p>
    <?php if (!$search): ?>
    <button onclick="openModal('createOrgModal')" class="btn btn-primary btn-md">Create Organisation</button>
    <?php endif; ?>
  </div>
  <?php else: ?>
  <div style="overflow-x:auto">
    <table class="data-table">
      <thead>
        <tr>
          <th>Organisation</th>
          <th>Type</th>
          <th>Contact</th>
          <th>Staff</th>
          <th>MT Balance</th>
          <th>Status</th>
          <th>Created</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($orgs as $o):
          $status_cls = match($o['status']) {
            'active'    => 'badge-success',
            'suspended' => 'badge-error',
            default     => 'badge-muted'
          };
        ?>
        <tr>
          <td>
            <div style="font-weight:700;font-size:.88rem"><?php echo h($o['name']); ?></div>
            <?php if ($o['email']): ?>
            <div style="font-size:.74rem;color:var(--text-muted)"><?php echo h($o['email']); ?></div>
            <?php endif; ?>
          </td>
          <td><span class="badge badge-info"><?php echo h(ucfirst($o['type'])); ?></span></td>
          <td style="font-size:.82rem"><?php echo h($o['contact_person'] ?: '—'); ?></td>
          <td>
            <span style="font-weight:700"><?php echo $o['staff_count']; ?></span>
            <span style="font-size:.75rem;color:var(--text-muted)"> staff</span>
          </td>
          <td style="font-weight:700;color:var(--success)">₦<?php echo number_format($o['total_mt_balance'], 2); ?></td>
          <td><span class="badge <?php echo $status_cls; ?>"><?php echo ucfirst($o['status']); ?></span></td>
          <td style="font-size:.8rem;color:var(--text-muted)"><?php echo date('M j, Y', strtotime($o['created_at'])); ?></td>
          <td>
            <div style="display:flex;gap:6px">
              <a href="organization_view.php?id=<?php echo $o['id']; ?>" class="btn btn-secondary btn-sm">View</a>
              <a href="organization_edit.php?id=<?php echo $o['id']; ?>" class="btn btn-secondary btn-sm">Edit</a>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php endif; ?>
</div>

</div>

<!-- Create Organisation Modal -->
<div class="modal-backdrop" id="createOrgModal">
  <div class="modal" style="max-width:640px;max-height:92vh;overflow-y:auto">
    <div class="modal-header" style="position:sticky;top:0;background:#fff;z-index:1">
      <h3>Create Organisation</h3>
      <button class="modal-close" onclick="closeModal('createOrgModal')">
        <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="create">
      <div class="modal-body">

        <?php if ($error && !$success): ?>
        <div class="alert alert-error" style="margin-bottom:16px"><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; ?>

        <p style="font-size:.82rem;font-weight:700;color:var(--text-muted);text-transform:uppercase;letter-spacing:.08em;margin-bottom:14px">Organisation Details</p>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px">
          <div class="form-group" style="grid-column:1/-1">
            <label>Organisation Name <span style="color:var(--error)">*</span></label>
            <input type="text" name="name" class="form-control" placeholder="General Hospital Lagos" required value="<?php echo h($_POST['name'] ?? ''); ?>">
          </div>
          <div class="form-group">
            <label>Organisation Type <span style="color:var(--error)">*</span></label>
            <select name="type" class="form-control" required>
              <option value="">— Select type —</option>
              <?php foreach (['hospital','school','company','government','ngo','other'] as $t): ?>
              <option value="<?php echo $t; ?>" <?php echo ($_POST['type']??'')===$t?'selected':''; ?>><?php echo ucfirst($t); ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="form-group">
            <label>Contact Person</label>
            <input type="text" name="contact_person" class="form-control" placeholder="Dr. Amina Bello" value="<?php echo h($_POST['contact_person'] ?? ''); ?>">
          </div>
          <div class="form-group">
            <label>Organisation Email</label>
            <input type="email" name="email" class="form-control" placeholder="hr@hospital.gov.ng" value="<?php echo h($_POST['email'] ?? ''); ?>">
          </div>
          <div class="form-group">
            <label>Phone</label>
            <input type="tel" name="phone" class="form-control" placeholder="+234 800 000 0000" value="<?php echo h($_POST['phone'] ?? ''); ?>">
          </div>
          <div class="form-group" style="grid-column:1/-1">
            <label>Address</label>
            <input type="text" name="address" class="form-control" placeholder="123 Hospital Road, Lagos" value="<?php echo h($_POST['address'] ?? ''); ?>">
          </div>
        </div>

        <hr style="border:none;border-top:1px solid var(--border);margin:18px 0">
        <p style="font-size:.82rem;font-weight:700;color:var(--text-muted);text-transform:uppercase;letter-spacing:.08em;margin-bottom:14px">Organisation Administrator</p>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px">
          <div class="form-group" style="grid-column:1/-1">
            <label>Admin Full Name <span style="color:var(--error)">*</span></label>
            <input type="text" name="admin_name" class="form-control" placeholder="Aisha Mohammed" required value="<?php echo h($_POST['admin_name'] ?? ''); ?>">
          </div>
          <div class="form-group">
            <label>Admin Email <span style="color:var(--error)">*</span></label>
            <input type="email" name="admin_email" class="form-control" placeholder="admin@hospital.gov.ng" required value="<?php echo h($_POST['admin_email'] ?? ''); ?>">
          </div>
          <div class="form-group">
            <label>Admin Password <span style="color:var(--error)">*</span></label>
            <input type="password" name="admin_password" class="form-control" placeholder="Min. 8 characters" minlength="8" required>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-md" onclick="closeModal('createOrgModal')">Cancel</button>
        <button type="submit" class="btn btn-primary btn-md">
          <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round" width="15" height="15"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
          Create Organisation
        </button>
      </div>
    </form>
  </div>
</div>

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