<?php
@ini_set('display_errors','1'); @error_reporting(E_ALL);

require_once __DIR__ . '/../includes/auth.php';
require_login(); // provides $con + csrf helpers

global $con;

/* =========================
   Config / Tables
========================= */
$TABLE  = 'jos_app_crm_lead_sources';
$MENUTBL = 'jos_admin_menus';

/* =========================
   Tiny utils
========================= */
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function clean($v){ return trim((string)$v); }

function keep_params(array $changes = []) {
  $qs = $_GET;
  foreach ($changes as $k=>$v) {
    if ($v===null) unset($qs[$k]);
    else $qs[$k]=$v;
  }
  $q = http_build_query($qs);
  if ($q) return '?'.$q;
  $script = $_SERVER['SCRIPT_NAME'] ?? ($_SERVER['PHP_SELF'] ?? basename(__FILE__));
  return $script;
}

function table_exists(mysqli $con, string $name): bool {
  $name = $con->real_escape_string($name);
  $rs = $con->query("SHOW TABLES LIKE '$name'");
  return ($rs && $rs->num_rows > 0);
}
function col_exists(mysqli $con, string $table, string $col): bool {
  $t = $con->real_escape_string($table);
  $c = $con->real_escape_string($col);
  $r = $con->query("SHOW COLUMNS FROM `$t` LIKE '$c'");
  return ($r && $r->num_rows > 0);
}

/* =========================
   Ensure schema
========================= */
function ensure_schema(mysqli $con, string $TABLE){
  if (!col_exists($con,$TABLE,'source_name')) {
    $con->query("ALTER TABLE `$TABLE` ADD `source_name` VARCHAR(190) NOT NULL");
  }
  if (!col_exists($con,$TABLE,'is_active')) {
    $con->query("ALTER TABLE `$TABLE` ADD `is_active` TINYINT(1) NOT NULL DEFAULT 1");
  }
  if (!col_exists($con,$TABLE,'sort_order')) {
    $con->query("ALTER TABLE `$TABLE` ADD `sort_order` INT NOT NULL DEFAULT 0");
  } else {
    $con->query("ALTER TABLE `$TABLE` MODIFY `sort_order` INT NOT NULL DEFAULT 0");
  }
  if (!col_exists($con,$TABLE,'created_at')) {
    $con->query("ALTER TABLE `$TABLE` ADD `created_at` DATETIME NULL DEFAULT NULL");
  }
}
ensure_schema($con,$TABLE);

/* =========================
   Current menu (for title + ACL)
========================= */
function current_script_paths(): array {
  $script = $_SERVER['SCRIPT_NAME'] ?? '';
  $req    = parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH) ?: $script;

  $variants = [];
  $variants[] = $script;
  $variants[] = $req;
  $variants[] = preg_replace('#^/beta#','', $script);
  $variants[] = preg_replace('#^/beta#','', $req);

  return array_values(array_unique(array_filter($variants, fn($p)=> (string)$p !== '')));
}

function fetch_menu_info(mysqli $con, string $MENUTBL): array {
  $out = ['id'=>0, 'menu_name'=>'CRM Lead Source', 'menu_link'=>''];
  if (!table_exists($con, $MENUTBL)) return $out;

  $paths = current_script_paths();

  foreach ($paths as $p) {
    $sql = "SELECT id, menu_name, menu_link FROM `$MENUTBL` WHERE menu_link=? LIMIT 1";
    if ($st = $con->prepare($sql)) {
      $st->bind_param('s', $p);
      $st->execute();
      if ($r = $st->get_result()->fetch_assoc()) { $st->close(); return $r; }
      $st->close();
    }
  }

  foreach ($paths as $p) {
    $like = '%'.$p;
    $sql = "SELECT id, menu_name, menu_link FROM `$MENUTBL`
            WHERE menu_link LIKE ? ORDER BY LENGTH(menu_link) DESC LIMIT 1";
    if ($st = $con->prepare($sql)) {
      $st->bind_param('s', $like);
      $st->execute();
      if ($r = $st->get_result()->fetch_assoc()) { $st->close(); return $r; }
      $st->close();
    }
  }

  return $out;
}

$menu = fetch_menu_info($con, $MENUTBL);
$page_title = $menu['menu_name'] ?: 'CRM Lead Source';
$MENU_ID    = (int)($menu['id'] ?? 0);

/* =========================
   Access control
========================= */
function user_can(string $action, int $menu_id, mysqli $con): bool {
  $action = strtolower($action);
  $valid  = ['view','add','edit','delete'];
  if (!in_array($action, $valid, true)) return false;

  // Session-based (if present)
  $sess = $_SESSION ?? [];
  if (!empty($sess['user_permissions']) && is_array($sess['user_permissions'])) {
    if ($menu_id && isset($sess['user_permissions'][$menu_id][$action])) {
      return (bool)$sess['user_permissions'][$menu_id][$action];
    }
    foreach (current_script_paths() as $k) {
      if (isset($sess['user_permissions'][$k][$action])) return (bool)$sess['user_permissions'][$k][$action];
    }
  }

  // DB fallback by role_id
  $me = $sess['admin_user'] ?? [];
  $role_id = (int)($me['role_id'] ?? 0);
  if ($role_id <= 0 || $menu_id <= 0) return false;

  $MAP1 = 'jos_admin_rolemenus';
  $MAP2 = 'jos_admin_role_menu';
  $mapTable = table_exists($con, $MAP1) ? $MAP1 : (table_exists($con, $MAP2) ? $MAP2 : '');
  if ($mapTable === '') return false;

  $cols = ['view'=>'can_view','add'=>'can_add','edit'=>'can_edit','delete'=>'can_delete'];
  $col  = $cols[$action];

  $sql = "SELECT $col AS allowed FROM `$mapTable` WHERE role_id=? AND menu_id=? LIMIT 1";
  if ($st = $con->prepare($sql)) {
    $st->bind_param('ii', $role_id, $menu_id);
    $st->execute();
    $res = $st->get_result()->fetch_assoc();
    $st->close();
    return (isset($res['allowed']) && (int)$res['allowed'] === 1);
  }
  return false;
}

/* Gate view */
if (!user_can('view', $MENU_ID, $con)) {
  http_response_code(403);
  ?>
  <!doctype html>
  <meta charset="utf-8">
  <link rel="stylesheet" href="/adminconsole/assets/ui.css">
  <div class="card" style="max-width:680px;margin:24px auto">
    <h3 style="margin-top:0"><?=h($page_title)?></h3>
    <div class="badge off" style="margin:8px 0">You are not authorized to view this content.</div>
  </div>
  <?php
  exit;
}

/* =========================
   Flash redirect helper
========================= */
function flash_redirect(string $msg='Saved'){
  $qs = $_GET; unset($qs['add'], $qs['edit']);
  $qs['ok'] = $msg;
  header('Location: ?'.http_build_query($qs));
  exit;
}

/* =========================
   POST handling
========================= */
$err='';

if ($_SERVER['REQUEST_METHOD']==='POST') {
  if (!verify_csrf($_POST['csrf'] ?? null)) {
    $err = 'Invalid request.';
  } else {

    // Save (insert/update)
    if (isset($_POST['save'])) {
      $id        = (int)($_POST['id'] ?? 0);
      $name      = clean($_POST['source_name'] ?? '');
      $sort_order= (int)($_POST['sort_order'] ?? 0);
      $active    = (int)($_POST['is_active'] ?? 1);

      if ($id > 0 && !user_can('edit', $MENU_ID, $con)) {
        $err = 'You are not authorized to edit.';
      } elseif ($id === 0 && !user_can('add', $MENU_ID, $con)) {
        $err = 'You are not authorized to add.';
      } elseif ($name === '') {
        $err = 'Source Name is required.';
      } else {
        if ($id > 0) {
          $st = $con->prepare("UPDATE `$TABLE` SET source_name=?, sort_order=?, is_active=? WHERE id=?");
          $st->bind_param('siii', $name, $sort_order, $active, $id);
          if ($st->execute()) { $st->close(); flash_redirect('Updated successfully'); }
          $err='Update failed'; $st->close();
        } else {
          $st = $con->prepare("INSERT INTO `$TABLE` (source_name, sort_order, is_active, created_at)
                               VALUES (?,?,?,NOW())");
          $st->bind_param('sii', $name, $sort_order, $active);
          if ($st->execute()) { $st->close(); flash_redirect('Saved successfully'); }
          $err='Insert failed'; $st->close();
        }
      }
    }

    // Delete
    if (isset($_POST['delete'])) {
      if (!user_can('delete', $MENU_ID, $con)) {
        $err = 'You are not authorized to delete.';
      } else {
        $id = (int)($_POST['id'] ?? 0);
        $st = $con->prepare("DELETE FROM `$TABLE` WHERE id=?");
        $st->bind_param('i', $id);
        if ($st->execute()) { $st->close(); flash_redirect('Deleted successfully'); }
        $err='Delete failed'; $st->close();
      }
    }
  }
}

/* =========================
   Mode
========================= */
$mode = (isset($_GET['edit']) || isset($_GET['add'])) ? 'form' : 'list';

if ($mode==='form') {
  if (isset($_GET['add']) && !user_can('add', $MENU_ID, $con)) { $mode='denied_form'; $err='You are not authorized to add.'; }
  if (isset($_GET['edit']) && !user_can('edit', $MENU_ID, $con)) { $mode='denied_form'; $err='You are not authorized to edit.'; }
}

/* =========================
   Edit row
========================= */
$edit=null;
if ($mode==='form' && isset($_GET['edit'])) {
  $eid=(int)$_GET['edit'];
  $st=$con->prepare("SELECT id,source_name,is_active,sort_order,created_at FROM `$TABLE` WHERE id=?");
  $st->bind_param('i',$eid);
  $st->execute();
  $edit=$st->get_result()->fetch_assoc();
  $st->close();
}

/* =========================
   Filters
========================= */
$q = trim($_GET['q'] ?? '');
$all = isset($_GET['all']);
$lim = $all ? 0 : 50;

$where = " WHERE 1=1 ";
$bind=[]; $type='';
if ($q!=='') { $where .= " AND source_name LIKE ?"; $bind[]="%$q%"; $type.='s'; }

/* =========================
   Counts / list
========================= */
$st=$con->prepare("SELECT COUNT(*) c FROM `$TABLE` $where");
if ($bind) $st->bind_param($type, ...$bind);
$st->execute();
$total = (int)$st->get_result()->fetch_assoc()['c'];
$st->close();

$sql = "SELECT id,source_name,is_active,sort_order,created_at
        FROM `$TABLE`
        $where
        ORDER BY sort_order ASC, id DESC";
if (!$all) $sql .= " LIMIT $lim";

$st=$con->prepare($sql);
if ($bind) $st->bind_param($type, ...$bind);
$st->execute();
$rs=$st->get_result();
$rows=[];
while($r=$rs->fetch_assoc()) $rows[]=$r;
$st->close();

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

<h2 style="margin:8px 0 12px"><?=h($page_title)?></h2>

<?php if ($mode==='denied_form'): ?>
  <div class="card" style="max-width:760px">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
      <h3 style="margin:0">Access denied</h3>
      <a class="btn gray" href="<?=h(keep_params(['edit'=>null,'add'=>null]))?>">Back to List</a>
    </div>
    <?php if($err): ?><div class="badge off" style="margin:8px 0"><?=h($err)?></div><?php endif; ?>
    <p style="color:#9ca3af;margin:8px 0">You don't have permission to perform this action.</p>
  </div>

<?php elseif ($mode==='list'): ?>

  <?php if(isset($_GET['ok'])): ?><div class="alert ok"><?=h($_GET['ok'])?></div><?php endif; ?>

  <div class="card">
    <div class="toolbar">
      <form method="get" class="search">
        <input type="text" name="q" class="inp" placeholder="Search lead source..." value="<?=h($q)?>">
        <button class="btn gray" type="submit">Search</button>
        <?php if(!$all && $total>$lim): ?>
          <a class="btn gray" href="<?=h(keep_params(['all'=>1]))?>">View All (<?=$total?>)</a>
        <?php endif; ?>
        <?php if($all): ?>
          <a class="btn gray" href="<?=h(keep_params(['all'=>null]))?>">Last 50</a>
        <?php endif; ?>
      </form>

      <?php if (user_can('add', $MENU_ID, $con)): ?>
        <a class="btn green" href="<?=h(keep_params(['add'=>1]))?>">Add New</a>
      <?php endif; ?>
    </div>

    <div style="margin:8px 0;color:#9ca3af">
      Showing <strong><?= !$all ? count($rows) : $total ?></strong> of <strong><?= $total ?></strong>
      <?= $q!=='' ? 'for “'.h($q).'”' : '' ?>
      <?= !$all ? '(sorted by Sort Order)' : '' ?>
    </div>

    <div class="table-wrap">
      <table>
        <thead>
          <tr>
            <th>SR No</th>
            <th>Source Name</th>
            <th>Sort</th>
            <th>Status</th>
            <th>Created</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
        <?php if(!$rows): ?>
          <tr><td colspan="6" style="color:#9ca3af">No records</td></tr>
        <?php endif; ?>

        <?php $sr=0; foreach($rows as $r): $sr++; ?>
          <tr>
            <td><?=$sr?></td>
            <td><?=h($r['source_name'])?></td>
            <td><?= (int)$r['sort_order'] ?></td>
            <td><span class="badge <?=((int)$r['is_active']===1)?'on':'off'?>">
              <?=((int)$r['is_active']===1)?'Active':'Inactive'?>
            </span></td>
            <td style="white-space:nowrap"><?=h($r['created_at'] ?? '—')?></td>
            <td style="white-space:nowrap">
              <?php if (user_can('edit', $MENU_ID, $con)): ?>
                <a class="btn gray" href="<?=h(keep_params(['edit'=>(int)$r['id']]))?>">Edit</a>
              <?php endif; ?>

              <?php if (user_can('delete', $MENU_ID, $con)): ?>
                <form method="post" style="display:inline" onsubmit="return confirm('Delete this record?');">
                  <input type="hidden" name="csrf" value="<?=h(csrf_token())?>">
                  <input type="hidden" name="id" value="<?=$r['id']?>">
                  <button class="btn red" name="delete" type="submit">Delete</button>
                </form>
              <?php endif; ?>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>

<?php else: /* form (allowed) */ ?>

  <div class="card" style="max-width:760px">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">
      <h3 style="margin:0"><?= $edit ? 'Edit Lead Source' : 'Add Lead Source' ?></h3>
      <a class="btn gray" href="<?=h(keep_params(['edit'=>null,'add'=>null]))?>">Back to List</a>
    </div>

    <?php if($err): ?><div class="badge off" style="margin:8px 0"><?=h($err)?></div><?php endif; ?>

    <form method="post"
          style="display:grid;grid-template-columns:1fr 1fr;gap:14px 16px;align-items:end">

      <input type="hidden" name="csrf" value="<?=h(csrf_token())?>">
      <?php if($edit): ?><input type="hidden" name="id" value="<?=$edit['id']?>"><?php endif; ?>

      <div>
        <label>Source Name <span style="color:#ef4444">*</span></label>
        <input class="inp" name="source_name" required
               placeholder="e.g. Referral, Walk-in"
               value="<?=h($edit['source_name'] ?? '')?>">
      </div>

      <div>
        <label>Sort Order</label>
        <input class="inp" type="number" name="sort_order" min="0"
               value="<?=h($edit['sort_order'] ?? 0)?>">
      </div>

      <div>
        <label>Status</label>
        <?php $st = isset($edit['is_active']) ? (int)$edit['is_active'] : 1; ?>
        <select class="inp" name="is_active">
          <option value="1" <?=$st===1?'selected':''?>>Active</option>
          <option value="0" <?=$st===0?'selected':''?>>Inactive</option>
        </select>
      </div>

      <div></div>

      <div style="grid-column:1/-1;display:flex;gap:10px;margin-top:6px">
        <button class="btn green" name="save" type="submit">Save</button>
        <a class="btn gray" href="<?=h(keep_params(['edit'=>null,'add'=>null]))?>">Back</a>
      </div>
    </form>
  </div>

<?php endif; ?>

<?php
echo ob_get_clean();
