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

$page_title = 'Languages Master';
$TABLE = 'jos_crm_languages';

/* ---------- helpers ---------- */
function keep_params(array $changes = []) {
  $qs = $_GET;
  foreach ($changes as $k=>$v) {
    if ($v === null) unset($qs[$k]);
    else $qs[$k] = $v;
  }
  return '?' . http_build_query($qs);
}
function clean($v){ return trim((string)$v); }
function col_exists($con,$table,$col){
  $r=mysqli_query($con,"SHOW COLUMNS FROM `$table` LIKE '".mysqli_real_escape_string($con,$col)."'");
  return ($r && mysqli_num_rows($r)>0);
}
function ensure_schema($con,$table){
  if(!col_exists($con,$table,'status')){
    mysqli_query($con,"ALTER TABLE `$table` ADD `status` TINYINT(1) NOT NULL DEFAULT 1");
  }
  if(!col_exists($con,$table,'orderby')){
    mysqli_query($con,"ALTER TABLE `$table` ADD `orderby` INT NOT NULL DEFAULT 0");
  } else {
    mysqli_query($con,"ALTER TABLE `$table` MODIFY `orderby` INT NOT NULL DEFAULT 0");
  }
}
ensure_schema($con,$TABLE);

/* ---------- permission & menu helpers ---------- */

/**
 * try_find_menu_record
 * Attempts to find a menu row for this script in likely menu tables.
 * Returns associative array of menu row when found, otherwise null.
 *
 * NOTE: updated to prefer 'jos_admin_menus' as requested.
 */
function try_find_menu_record($con){
  // prioritized candidate tables/columns (jos_admin_menus first as requested)
  $candidates = [
    // primary system table provided by the user
    ['table'=>'jos_admin_menus','cols'=>['link','path','url','route','component','title','name','label']],
    // fallbacks for other installs
    ['table'=>'jos_menu_master','cols'=>['link','url','path','title','name','label']],
    ['table'=>'menu_master','cols'=>['link','url','path','title','name','label']],
    ['table'=>'jos_menu','cols'=>['link','url','path','title','name','label']],
    ['table'=>'menus','cols'=>['link','url','path','title','name','label']],
  ];

  $script = basename($_SERVER['PHP_SELF']);
  foreach($candidates as $c){
    $t = $c['table'];
    // check table exists
    $r = mysqli_query($con, "SHOW TABLES LIKE '".mysqli_real_escape_string($con,$t)."'");
    if (!$r || mysqli_num_rows($r)===0) continue;
    // for each candidate column, check presence then try to match script
    foreach($c['cols'] as $col){
      $colEsc = mysqli_real_escape_string($con, $col);
      // check column exists in table
      $cr = mysqli_query($con, "SHOW COLUMNS FROM `".mysqli_real_escape_string($con,$t)."` LIKE '$colEsc'");
      if (!$cr || mysqli_num_rows($cr)===0) continue;
      $esc = mysqli_real_escape_string($con, $script);
      // try to match script filename anywhere in column value
      $q = "SELECT * FROM `$t` WHERE `$col` LIKE '%$esc%' LIMIT 1";
      $res = mysqli_query($con, $q);
      if ($res && mysqli_num_rows($res)>0){
        return mysqli_fetch_assoc($res);
      }
    }
  }
  return null;
}

/**
 * can($action)
 * Action is one of: view, add, edit, delete
 * Checks session user keys first, then menu master row. If nothing found, defaults to true.
 */
function can($action){
  $me = $_SESSION['admin_user'] ?? [];
  $action = strtolower($action);

  $sess_keys = [
    'view' => ['can_view','can_view_languages','perm_view'],
    'add'  => ['can_add','can_add_languages','perm_add'],
    'edit' => ['can_edit','can_edit_languages','perm_edit'],
    'delete'=> ['can_delete','can_delete_languages','perm_delete'],
  ];

  if (isset($sess_keys[$action])){
    foreach($sess_keys[$action] as $k){
      if (array_key_exists($k, $me)){
        return (bool)$me[$k];
      }
    }
    if (!empty($me['permissions']) && is_array($me['permissions'])){
      if (array_key_exists($action, $me['permissions'])) return (bool)$me['permissions'][$action];
      if (array_key_exists('languages_'.$action, $me['permissions'])) return (bool)$me['permissions']['languages_'.$action];
    }
  }

  static $menu_row_cached = '__notloaded__';
  global $con;
  if ($menu_row_cached === '__notloaded__'){
    $menu_row_cached = try_find_menu_record($con);
  }
  $m = $menu_row_cached;
  if ($m && is_array($m)){
    $menu_cols = [
      'view'=> ['can_view','perm_view','view','allow_view'],
      'add' => ['can_add','perm_add','add','allow_add'],
      'edit'=> ['can_edit','perm_edit','edit','allow_edit'],
      'delete'=> ['can_delete','perm_delete','delete','allow_delete'],
    ];
    if (isset($menu_cols[$action])){
      foreach($menu_cols[$action] as $col){
        if (array_key_exists($col, $m)){
          $v = $m[$col];
          if ($v === null || $v === '') continue;
          if (is_numeric($v)) return ((int)$v)===1;
          $vl = strtolower((string)$v);
          return in_array($vl, ['1','y','yes','true','allow','on']);
        }
      }
    }
  }

  // default allow for backward compatibility; change to false if you want deny-by-default
  return true;
}

/* flash redirect helper -- preserve current list/filter params when redirecting back */
function back_to_list($msg=''){
  // Remove add/edit parameters but keep filters (q, level, sort, all, etc.)
  $base = $_SERVER['PHP_SELF'] . keep_params(['add'=>null,'edit'=>null]);
  if ($msg !== ''){
    $sep = (strpos($base,'?') === false) ? '?' : '&';
    $base .= $sep . 'ok=' . urlencode($msg);
  }
  header('Location: ' . $base);
  exit;
}

/* authorize viewing: if user cannot view, show message and stop */
if (!can('view')){
  http_response_code(403);
  echo '<link rel="stylesheet" href="/adminconsole/assets/ui.css">';
  echo '<div class="card"><h3>Access Denied</h3><div class="err">You do not have permission to view this page.</div></div>';
  exit;
}

$me   = $_SESSION['admin_user'] ?? [];
$myid = (int)($me['id'] ?? 0);

$ok  = clean($_GET['ok'] ?? '');
$err = '';

/* ---------- POST ---------- */
if ($_SERVER['REQUEST_METHOD']==='POST'){
  if (!verify_csrf($_POST['csrf'] ?? null)) {
    $err='Invalid request.';
  } else {
    if (isset($_POST['save'])) {
      $id = (int)($_POST['id'] ?? 0);
      // permission checks: new record requires add, existing requires edit
      if ($id>0 && !can('edit')) { $err='Permission denied.'; }
      if ($id===0 && !can('add')) { $err='Permission denied.'; }

      if ($err==='') {
        $name   = clean($_POST['name'] ?? '');
        $status = (int)($_POST['status'] ?? 1);
        $ord    = (int)($_POST['orderby'] ?? 0);

        if ($name==='') $err='Language name is required.';
        else {
          $dup_sql = "SELECT id FROM $TABLE WHERE LOWER(name)=LOWER(?)";
          if ($id>0) $dup_sql .= " AND id<>?";
          $st = $con->prepare($dup_sql." LIMIT 1");
          if ($id>0) $st->bind_param('si',$name,$id); else $st->bind_param('s',$name);
          $st->execute(); $dup=$st->get_result()->fetch_assoc(); $st->close();

          if ($dup){ $err='This language already exists.'; }
          else {
            if ($ord<=0){
              $r = mysqli_query($con,"SELECT COALESCE(MAX(orderby),0)+1 nxt FROM $TABLE");
              $ord = (int)($r ? mysqli_fetch_assoc($r)['nxt'] : 1);
            }

            $hasCreated = col_exists($con,$TABLE,'created_by');
            $hasMod     = col_exists($con,$TABLE,'modified_by');

            if ($id>0){
              if ($hasMod){
                $sql="UPDATE $TABLE SET name=?, status=?, orderby=?, modified_by=? WHERE id=?";
                $st=$con->prepare($sql); $st->bind_param('siiii',$name,$status,$ord,$myid,$id);
              } else {
                $sql="UPDATE $TABLE SET name=?, status=?, orderby=? WHERE id=?";
                $st=$con->prepare($sql); $st->bind_param('siii',$name,$status,$ord,$id);
              }
              if ($st->execute()){ $st->close(); back_to_list('Updated successfully.'); }
              $err='Update failed.'; $st->close();
            } else {
              if ($hasCreated && $hasMod){
                $sql="INSERT INTO $TABLE (name,status,orderby,created_by,modified_by) VALUES (?,?,?,?,?)";
                $st=$con->prepare($sql); $st->bind_param('siiii',$name,$status,$ord,$myid,$myid);
              } else {
                $sql="INSERT INTO $TABLE (name,status,orderby) VALUES (?,?,?)";
                $st=$con->prepare($sql); $st->bind_param('sii',$name,$status,$ord);
              }
              if ($st->execute()){ $st->close(); back_to_list('Added successfully.'); }
              $err='Insert failed.'; $st->close();
            }
          }
        }
      }
    }
    if (isset($_POST['delete'])) {
      if (!can('delete')) {
        $err = 'Permission denied.';
      } else {
        $id=(int)($_POST['id'] ?? 0);
        $st=$con->prepare("DELETE FROM $TABLE WHERE id=?");
        $st->bind_param('i',$id);
        if ($st->execute()){ $st->close(); back_to_list('Deleted successfully.'); }
        $err='Delete failed.'; $st->close();
      }
    }
  }
}

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

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

/* ---------- filters ---------- */
$q      = clean($_GET['q'] ?? '');
$levelS = clean($_GET['level'] ?? ''); // order level filter (exact)
$sort   = clean($_GET['sort'] ?? 'order_asc'); // sort selector
$all    = isset($_GET['all']); $lim = $all ? 0 : 50;

$where=" WHERE 1=1 "; $bind=[]; $type='';
if ($q!==''){ $like="%$q%"; $where.=" AND name LIKE ?"; $bind[]=$like; $type.='s'; }
if ($levelS !== '' && is_numeric($levelS)){ $lvl=(int)$levelS; $where.=" AND orderby=?"; $bind[]=$lvl; $type.='i'; }

/* sort mapping */
switch ($sort){
  case 'order_desc': $order="ORDER BY orderby DESC, id DESC"; break;
  case 'name_asc'  : $order="ORDER BY name ASC"; break;
  case 'name_desc' : $order="ORDER BY name DESC"; break;
  case 'id_asc'    : $order="ORDER BY id ASC"; break;
  case 'id_desc'   : $order="ORDER BY id DESC"; break;
  default          : $order="ORDER BY orderby ASC, id DESC";
}

/* ---------- 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,status,orderby FROM $TABLE $where $order";
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();

/* try to load title from menu master if available */
$menu_row = try_find_menu_record($con);
if ($menu_row) {
  if (!empty($menu_row['title'])) $page_title = $menu_row['title'];
  elseif (!empty($menu_row['name'])) $page_title = $menu_row['name'];
  elseif (!empty($menu_row['label'])) $page_title = $menu_row['label'];
}

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

<?php if ($mode==='list'): ?>
  <div class="card">
    <div class="toolbar">
      <form method="get" class="search">
        <input type="text" name="q" class="inp" placeholder="Search language..." value="<?=htmlspecialchars($q)?>">
        <input type="number" name="level" class="inp small" placeholder="Order level" value="<?=htmlspecialchars($levelS)?>">
        <select name="sort" class="inp small" title="Sort by">
          <?php
            $opts = [
              'order_asc'  => 'Order Level ↑',
              'order_desc' => 'Order Level ↓',
              'name_asc'   => 'Name A–Z',
              'name_desc'  => 'Name Z–A',
              'id_desc'    => 'Newest first',
              'id_asc'     => 'Oldest first',
            ];
            foreach($opts as $k=>$v){
              $sel = ($sort===$k)?'selected':'';
              echo "<option value=\"$k\" $sel>$v</option>";
            }
          ?>
        </select>
        <button class="btn gray" type="submit">Search</button>
        <?php if(!$all && $total>$lim): ?><a class="btn gray" href="<?=htmlspecialchars(keep_params(['all'=>1]))?>">View All (<?=$total?>)</a><?php endif; ?>
        <?php if($all): ?><a class="btn gray" href="<?=htmlspecialchars(keep_params(['all'=>null]))?>">Last 50</a><?php endif; ?>
      </form>
      <?php if (can('add')): ?>
        <a class="btn green" href="<?=htmlspecialchars(keep_params(['add'=>1,'edit'=>null]))?>">Add New</a>
      <?php else: ?>
        <button class="btn green" disabled title="You don't have permission to add new">Add New</button>
      <?php endif; ?>
    </div>

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

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

    <div style="margin:8px 0;color:#9ca3af">
      Showing <strong><?= !$all ? count($rows) : $total ?></strong> of <strong><?= $total ?></strong>
      <?= $q!=='' ? 'for “'.htmlspecialchars($q).'”' : '' ?>
      <?php
        $label = $opts[$sort] ?? 'Order Level ↑';
        echo '(sorted: '.htmlspecialchars($label).')';
      ?>
    </div>

    <div class="table-wrap">
      <table>
        <thead><tr>
          <th>SR No</th><th>Name</th><th class="num">Order Level</th><th>Status</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><?=htmlspecialchars($r['name'])?></td>
            <td class="num"><?= (int)$r['orderby'] ?></td>
            <td><span class="badge <?=$r['status']?'on':'off'?>"><?=$r['status']?'Active':'Inactive'?></span></td>
            <td>
              <?php if (can('edit')): ?>
                <a class="btn gray" href="<?=htmlspecialchars(keep_params(['edit'=>(int)$r['id'],'add'=>null]))?>">Edit</a>
              <?php else: ?>
                <button class="btn gray" disabled title="No edit permission">Edit</button>
              <?php endif; ?>

              <?php if (can('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="<?=$r['id']?>">
                  <button class="btn red" name="delete" type="submit">Delete</button>
                </form>
              <?php else: ?>
                <button class="btn red" disabled title="No delete permission">Delete</button>
              <?php endif; ?>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>

<?php else: /* form */ ?>
  <div class="card" style="max-width:720px">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
      <h3 style="margin:0"><?= $edit ? 'Edit Language' : 'Add Language' ?></h3>
      <a class="btn gray" href="<?=htmlspecialchars(keep_params(['edit'=>null,'add'=>null]))?>">Back to List</a>
    </div>

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

    <?php
      $is_edit = (bool)$edit;
      $allowed = $is_edit ? can('edit') : can('add');
      if (!$allowed):
    ?>
      <div class="err">You do not have permission to <?= $is_edit ? 'edit' : 'add' ?> languages.</div>
    <?php endif; ?>

    <form method="post" style="display:grid;grid-template-columns:1fr 1fr;gap:12px" autocomplete="off">
      <input type="hidden" name="csrf" value="<?=htmlspecialchars(csrf_token())?>">
      <?php if($edit): ?><input type="hidden" name="id" value="<?=$edit['id']?>"><?php endif; ?>

      <div style="grid-column:1/-1">
        <label>Name*</label>
        <input name="name" class="inp" required value="<?=htmlspecialchars($edit['name'] ?? '')?>" <?= $allowed ? '' : 'disabled'?>>
      </div>

      <div>
        <label>Order Level</label>
        <input name="orderby" type="number" class="inp" value="<?=htmlspecialchars((string)($edit['orderby'] ?? ''))?>" placeholder="Auto if blank/0" <?= $allowed ? '' : 'disabled'?>>
      </div>

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

      <div style="grid-column:1/-1">
        <?php if ($allowed): ?>
          <button class="btn green" name="save" type="submit">Save</button>
        <?php else: ?>
          <button class="btn green" disabled title="No permission">Save</button>
        <?php endif; ?>
      </div>
    </form>
  </div>
<?php endif; ?>

<?php
echo ob_get_clean();
