<?php
require_once __DIR__ . '/../includes/auth.php';
require_login();

$page_title = 'Gender Master';
$TABLE = 'jos_crm_gender';

$err = '';
$ok  = '';

/**
 * Simple permission helper.
 * - If your app defines current_user_can($cap) use that.
 * - Else it will try to read $_SESSION['user']['caps'] as an array.
 * - If neither exists, it returns true (so behavior remains the same).
 *
 * Replace/extend this with your real authorization calls as needed.
 */
function can(string $cap) {
    // Preferred hook if your system offers it
    if (function_exists('current_user_can')) {
        return current_user_can($cap);
    }

    // Session-based capabilities (common pattern)
    if (isset($_SESSION['user']['caps']) && is_array($_SESSION['user']['caps'])) {
        return in_array($cap, $_SESSION['user']['caps'], true);
    }

    // Unknown system -> default allow (to not break existing logic).
    // Change to `return false;` to lock down by default.
    return true;
}

/**
 * Resolve canonical page base for "Back to list" links.
 * Uses PHP_SELF (script path) to avoid preserving querystring.
 */
$LIST_URL = $_SERVER['PHP_SELF'];

/* ------------------ load menu title from jos_admin_menus (best-effort) ------------------ */
try {
    if (isset($con) && $con instanceof mysqli) {
        // Try to find menu title by matching link to this file name.
        $link_match = '%' . basename(__FILE__); // e.g. 'gender.php'
        $st = $con->prepare("SELECT title FROM jos_admin_menus WHERE link LIKE ? LIMIT 1");
        if ($st) {
            $st->bind_param('s', $link_match);
            $st->execute();
            $res = $st->get_result();
            if ($r = $res->fetch_assoc()) {
                $page_title = $r['title'] ?: $page_title;
            }
            $st->close();
        }
    }
} catch (Throwable $e) {
    // silently ignore DB errors here so we don't break the page if menu table doesn't exist.
}

/* ------------------ deny view if not allowed ------------------ */
if (!can('gender_view')) {
    http_response_code(403);
    echo '<div style="padding:18px;color:#fff;background:#7f1d1d;border-radius:6px">Access denied.</div>';
    exit;
}

// Handle POST (add/update/delete)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf($_POST['csrf'] ?? null)) {
        $err = 'Invalid request. Please refresh.';
    } else {
        // ADD / SAVE (Insert or Update)
        if (isset($_POST['save'])) {
            if (!can('gender_add') && !can('gender_edit')) {
                $err = 'You do not have permission to save records.';
            } else {
                $id     = (int)($_POST['id'] ?? 0);
                $name   = trim($_POST['name'] ?? '');
                $status = (int)($_POST['status'] ?? 1);

                if ($name === '') {
                    $err = 'Name is required.';
                } else {
                    if ($id > 0) {
                        // Edit permission check
                        if (!can('gender_edit')) {
                            $err = 'You do not have permission to edit records.';
                        } else {
                            $sql = "UPDATE $TABLE SET name = ?, status = ? WHERE id = ?";
                            $st  = $con->prepare($sql);
                            if ($st) {
                                $st->bind_param('sii', $name, $status, $id);
                                $ok  = $st->execute() ? 'Updated successfully' : ('Update failed: ' . $con->error);
                                $st->close();
                            } else {
                                $err = 'Prepare failed: ' . $con->error;
                            }
                        }
                    } else {
                        // Insert permission check
                        if (!can('gender_add')) {
                            $err = 'You do not have permission to add records.';
                        } else {
                            $sql = "INSERT INTO $TABLE (name, status) VALUES (?, ?)";
                            $st  = $con->prepare($sql);
                            if ($st) {
                                $st->bind_param('si', $name, $status);
                                $ok  = $st->execute() ? 'Added successfully' : ('Insert failed: ' . $con->error);
                                $st->close();
                            } else {
                                $err = 'Prepare failed: ' . $con->error;
                            }
                        }
                    }
                }
            }
        }

        // DELETE
        if (isset($_POST['delete']) && isset($_POST['id'])) {
            if (!can('gender_delete')) {
                $err = 'You do not have permission to delete records.';
            } else {
                $id = (int)$_POST['id'];
                $sql = "DELETE FROM $TABLE WHERE id = ?";
                $st  = $con->prepare($sql);
                if ($st) {
                    $st->bind_param('i', $id);
                    $ok  = $st->execute() ? 'Deleted successfully' : ('Delete failed: ' . $con->error);
                    $st->close();
                } else {
                    $err = 'Prepare failed: ' . $con->error;
                }
            }
        }
    }
}

// If editing, fetch row
$edit = null;
if (isset($_GET['edit'])) {
    $eid = (int)$_GET['edit'];
    $st  = $con->prepare("SELECT id, name, status FROM $TABLE WHERE id = ?");
    if ($st) {
        $st->bind_param('i', $eid);
        $st->execute();
        $edit = $st->get_result()->fetch_assoc();
        $st->close();
    }
}

// List rows (used only when not add-only and not editing)
$rows = [];
if (!$edit && !isset($_GET['add'])) {
    $res  = $con->query("SELECT id, name, status FROM $TABLE ORDER BY id DESC");
    while ($r = $res->fetch_assoc()) $rows[] = $r;
}

// ---------- View ----------
ob_start(); ?>
<link rel="stylesheet" href="/adminconsole/assets/ui.css">

<div class="page-header" style="display:flex;align-items:center;justify-content:space-between;margin-bottom:18px">
  <h2 style="margin:0"><?= htmlspecialchars($page_title) ?></h2>
</div>

<div class="grid">
  <?php
  // 1) Edit-only view: show the edit form and Back to list
  if ($edit): ?>
    <div class="card" style="width:100%;padding:18px;">
      <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px">
        <h3 style="margin:0"><?= 'Edit Gender' ?></h3>
        <a href="<?= htmlspecialchars($LIST_URL) ?>" class="btn gray" style="padding:8px 12px">Back to List</a>
      </div>

      <?php if($ok): ?><div class="msg ok"><?=htmlspecialchars($ok)?></div><?php endif; ?>
      <?php if($err): ?><div class="msg err"><?=htmlspecialchars($err)?></div><?php endif; ?>

      <form method="post" style="margin-top:8px">
        <input type="hidden" name="csrf" value="<?=htmlspecialchars(csrf_token())?>">
        <input type="hidden" name="id" value="<?= (int)$edit['id'] ?>">

        <div style="display:flex;gap:16px;align-items:flex-end;flex-wrap:wrap">
          <div style="flex:0 0 360px">
            <label for="name" style="display:block;margin-bottom:6px;color:#d1d5db">Name</label>
            <input id="name" name="name" required value="<?=htmlspecialchars($edit['name'] ?? '')?>" style="width:100%;padding:10px;border-radius:6px;background:#0b1220;color:#e6eef8;border:1px solid #192234">
          </div>

          <div style="flex:0 0 200px">
            <label for="status" style="display:block;margin-bottom:6px;color:#d1d5db">Status</label>
            <select id="status" name="status" style="width:100%;padding:10px;border-radius:6px;background:#0b1220;color:#e6eef8;border:1px solid #192234">
              <option value="1" <?=isset($edit['status']) && (int)$edit['status']===1 ? 'selected':''?>>Active</option>
              <option value="0" <?=isset($edit['status']) && (int)$edit['status']===0 ? 'selected':''?>>Inactive</option>
            </select>
          </div>

          <div style="flex:0 0 auto;margin-left:6px">
            <?php if (can('gender_edit')): ?>
              <button type="submit" name="save" class="btn" style="background:#16a34a;border-color:#16a34a;color:#fff;padding:10px 16px;border-radius:8px">Save</button>
            <?php else: ?>
              <button type="button" disabled class="btn" style="opacity:0.6;padding:10px 16px;border-radius:8px">Save (no permission)</button>
            <?php endif; ?>
          </div>
        </div>
      </form>
    </div>

  <?php
  // 2) Add-only view: when ?add=1 show only the add form (no list)
  elseif (isset($_GET['add'])): ?>
    <div class="card" style="width:100%;padding:18px;">
      <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px">
        <h3 style="margin:0">Add Gender</h3>
        <a href="<?= htmlspecialchars($LIST_URL) ?>" class="btn gray" style="padding:8px 12px">Back to List</a>
      </div>

      <?php if($ok): ?><div class="msg ok"><?=htmlspecialchars($ok)?></div><?php endif; ?>
      <?php if($err): ?><div class="msg err"><?=htmlspecialchars($err)?></div><?php endif; ?>

      <form method="post" style="margin-top:8px">
        <input type="hidden" name="csrf" value="<?=htmlspecialchars(csrf_token())?>">

        <div style="display:flex;gap:16px;align-items:flex-end;flex-wrap:wrap">
          <div style="flex:0 0 360px">
            <label for="name_add" style="display:block;margin-bottom:6px;color:#d1d5db">Name</label>
            <input id="name_add" name="name" required value="" style="width:100%;padding:10px;border-radius:6px;background:#0b1220;color:#e6eef8;border:1px solid #192234">
          </div>

          <div style="flex:0 0 200px">
            <label for="status_add" style="display:block;margin-bottom:6px;color:#d1d5db">Status</label>
            <select id="status_add" name="status" style="width:100%;padding:10px;border-radius:6px;background:#0b1220;color:#e6eef8;border:1px solid #192234">
              <option value="1">Active</option>
              <option value="0">Inactive</option>
            </select>
          </div>

          <div style="flex:0 0 auto;margin-left:6px">
            <?php if (can('gender_add')): ?>
              <button type="submit" name="save" class="btn" style="background:#16a34a;border-color:#16a34a;color:#fff;padding:10px 16px;border-radius:8px">Save</button>
            <?php else: ?>
              <button type="button" disabled class="btn" style="opacity:0.6;padding:10px 16px;border-radius:8px">Save (no permission)</button>
            <?php endif; ?>
          </div>
        </div>
      </form>
    </div>

  <?php
  // 3) Default list view: show list + green Add button
  else: ?>
    <div class="card" style="width:100%;padding:18px">
      <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:12px">
        <h3 style="margin:0">Gender List</h3>
        <div>
          <?php if (can('gender_add')): ?>
            <a class="btn" href="<?= htmlspecialchars($LIST_URL) . '?add=1' ?>" style="padding:8px 12px;background:#16a34a;border-color:#16a34a;color:#fff;border-radius:6px">+ Add Gender</a>
          <?php endif; ?>
        </div>
      </div>

      <table style="width:100%;border-collapse:collapse">
        <thead>
          <tr style="text-align:left;color:#94a3b8">
            <th style="padding:10px 6px;width:70px">ID</th>
            <th style="padding:10px 6px">Name</th>
            <th style="padding:10px 6px;width:120px">Status</th>
            <th style="padding:10px 6px;width:210px">Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php if(!$rows): ?>
            <tr><td colspan="4" style="color:#9ca3af;padding:14px">No records</td></tr>
          <?php endif; ?>
          <?php foreach($rows as $r): ?>
            <tr style="border-top:1px solid rgba(255,255,255,0.03)">
              <td style="padding:10px 6px;vertical-align:middle"><?= (int)$r['id'] ?></td>
              <td style="padding:10px 6px;vertical-align:middle"><?= htmlspecialchars($r['name']) ?></td>
              <td style="padding:10px 6px;vertical-align:middle">
                <span class="badge <?= $r['status']?'on':'off' ?>"><?= $r['status']?'Active':'Inactive' ?></span>
              </td>
              <td style="padding:10px 6px;vertical-align:middle">
                <?php if (can('gender_edit')): ?>
                  <a class="btn" href="<?= htmlspecialchars($LIST_URL . '?edit=' . (int)$r['id']) ?>">Edit</a>
                <?php else: ?>
                  <button class="btn" disabled style="opacity:0.6">Edit</button>
                <?php endif; ?>

                <?php if (can('gender_delete')): ?>
                  <form method="post" style="display:inline" onsubmit="return confirm('Delete this record?');">
                    <input type="hidden" name="csrf" value="<?=htmlspecialchars(csrf_token())?>">
                    <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                    <button class="btn danger" type="submit" name="delete" style="margin-left:8px">Delete</button>
                  </form>
                <?php else: ?>
                  <button class="btn danger" disabled style="margin-left:8px;opacity:0.6">Delete</button>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>

  <?php endif; ?>
</div>

<?php
echo ob_get_clean();
