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

require_once __DIR__ . '/../includes/auth.php';
require_login(); // also provides $con (mysqli)

global $con;

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

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

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 = mysqli_real_escape_string($con, $name);
  $rs = mysqli_query($con, "SHOW TABLES LIKE '$name'");
  return ($rs && mysqli_num_rows($rs) > 0);
}

/* =========================
   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, function($p){ return (string)$p !== ''; })));
}

function fetch_menu_info(mysqli $con, string $MENUTBL): array {
  $out = ['id'=>0, 'menu_name'=>'', '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 = '%'.mysqli_real_escape_string($con, $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'] ?: 'Caption Language Master';
$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;

  $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];
    }
    $paths = current_script_paths();
    foreach ($paths as $k) {
      if (isset($sess['user_permissions'][$k][$action])) return (bool)$sess['user_permissions'][$k][$action];
    }
  }

  $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;
}

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 (with ACL)
========================= */
$err=''; $ok='';
if ($_SERVER['REQUEST_METHOD']==='POST'){
  if (!verify_csrf($_POST['csrf'] ?? null)) {
    $err='Invalid request.';
  } else {
    if (isset($_POST['save'])) {
      $id   = (int)($_POST['id'] ?? 0);
      $name = clean($_POST['name'] ?? '');

      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 = 'Name is required.';
      } else {
        if ($id > 0) {
          $st = $con->prepare("SELECT id FROM `$TABLE` WHERE LOWER(name)=LOWER(?) AND id<>? LIMIT 1");
          $st->bind_param('si', $name, $id);
        } else {
          $st = $con->prepare("SELECT id FROM `$TABLE` WHERE LOWER(name)=LOWER(?) LIMIT 1");
          $st->bind_param('s', $name);
        }
        $st->execute();
        $dup = $st->get_result()->fetch_assoc();
        $st->close();

        if ($dup) {
          $err = 'Caption language already exists.';
        } elseif ($id > 0) {
          $st = $con->prepare("UPDATE `$TABLE` SET name=?, updated_at=NOW() WHERE id=?");
          $st->bind_param('si', $name, $id);
          if ($st->execute()) { $st->close(); flash_redirect('Updated successfully'); }
          $err = 'Update failed';
          $st->close();
        } else {
          $st = $con->prepare("INSERT INTO `$TABLE` (name, updated_at) VALUES (?, NOW())");
          $st->bind_param('s', $name);
          if ($st->execute()) { $st->close(); flash_redirect('Saved successfully'); }
          $err = 'Insert failed';
          $st->close();
        }
      }
    }

    if (isset($_POST['delete'])) {
      if (!user_can('delete', $MENU_ID, $con)) {
        $err = 'You are not authorized to delete.';
      } else {
        $id = (int)$_POST['id'];
        $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 (respect ACL for add/edit)
========================= */
$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,name,created_at,updated_at FROM `$TABLE` WHERE id=?");
  $st->bind_param('i',$eid);
  $st->execute();
  $edit=$st->get_result()->fetch_assoc();
  $st->close();
}

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

$where = " WHERE 1=1 ";
$bind=[]; $type='';
if ($q !== '') {
  $where .= " AND 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,name,created_at,updated_at FROM `$TABLE` $where ORDER BY 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; ?>
  <?php if($err): ?><div class="badge off" style="margin:8px 0"><?=h($err)?></div><?php endif; ?>

  <div class="card">
    <div class="toolbar">
      <form method="get" class="search">
        <input type="text" name="q" class="inp" placeholder="Search by language..." value="<?=h($q)?>">
        <button class="btn gray" type="submit">Search</button>
        <?php if($q !== ''): ?><a class="btn gray" href="<?=h(keep_params(['q'=>null]))?>">Clear</a><?php endif; ?>
        <?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 ? '(latest first)' : '' ?>
    </div>

    <div class="table-wrap">
      <table>
        <thead><tr>
          <th>SR No</th>
          <th>Name</th>
          <th>Created At</th>
          <th>Updated At</th>
          <th>Actions</th>
        </tr></thead>
        <tbody>
        <?php if(!$rows): ?><tr><td colspan="5" style="color:#9ca3af">No records</td></tr><?php endif; ?>
        <?php $sr=0; foreach($rows as $r): $sr++; ?>
          <tr>
            <td><?=$sr?></td>
            <td><?=h($r['name'])?></td>
            <td><?=h($r['created_at'] ?? '')?></td>
            <td><?=h($r['updated_at'] ?? '')?></td>
            <td>
              <?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: ?>
  <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"><?= $edit ? 'Edit Caption Language' : 'Add Caption Language' ?></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;gap:12px">
      <input type="hidden" name="csrf" value="<?=h(csrf_token())?>">
      <?php if($edit): ?><input type="hidden" name="id" value="<?=$edit['id']?>"><?php endif; ?>

      <div>
        <label>Name*</label>
        <input name="name" class="inp" required value="<?=h($edit['name'] ?? '')?>">
      </div>

      <div>
        <button class="btn green" name="save" type="submit">Save</button>
      </div>
    </form>
  </div>
<?php endif; ?>

<?php
echo ob_get_clean();
