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

global $con;

/**
 * ---------- Helper: load menu title & permissions ----------
 *
 * Behavior:
 *  - Tries to find menu entry in jos_admin_menus that corresponds to this script (by menu_link).
 *  - Accepts an explicit ?menu_id= for testing.
 *  - Normalizes a few path candidates (basename, SCRIPT_NAME, request path) when matching menu_link.
 *  - If found, loads title and checks role permissions (jos_admin_users_roles + jos_admin_rolemenus).
 *  - If DB tables are not present or queries fail, falls back to sensible defaults:
 *      * Page title fallback = 'OTP Report'
 *      * Permissions fallback = allow view, disallow add/edit/delete
 *
 * Notes:
 *  - This is intentionally defensive so it won't break if your admin schema differs slightly.
 *  - Adjust table/column names if your system uses different names.
 */

function safe_call($fn, $fallback = null) {
    try { return $fn(); } catch(Throwable $e) { return $fallback; }
}

function pacific_get_current_user_id() {
    // Prefer a framework function current_user() if available, otherwise session
    if(function_exists('current_user')) {
        $u = current_user();
        if(is_array($u) && isset($u['id'])) return (int)$u['id'];
        if(is_object($u) && isset($u->id)) return (int)$u->id;
    }
    if(!empty($_SESSION['user_id'])) return (int)$_SESSION['user_id'];
    if(!empty($_SESSION['uid'])) return (int)$_SESSION['uid'];
    return 0;
}

function pacific_get_menu_and_permissions($con) {
    $result = [
        'menu_id' => null,
        'title'   => 'OTP Report',
        'can_view'=> true,
        'can_add' => false,
        'can_edit'=> false,
        'can_delete'=> false,
    ];

    return safe_call(function() use($con, $result) {
        $res = $result;

        // Allow test override by menu_id in query string
        $menu_id_override = null;
        if(isset($_GET['menu_id']) && is_numeric($_GET['menu_id'])) {
            $menu_id_override = (int)$_GET['menu_id'];
        }

        if($menu_id_override) {
            $sql = "SELECT id, title, menu_link FROM jos_admin_menus WHERE id = ? LIMIT 1";
            $stmt = $con->prepare($sql);
            if($stmt) {
                $stmt->bind_param('i', $menu_id_override);
                $stmt->execute();
                $stmt->bind_result($mid, $mtitle, $mlink);
                if($stmt->fetch()) {
                    $res['menu_id'] = $mid;
                    $res['title'] = $mtitle ?: $res['title'];
                }
                $stmt->close();
            }
        } else {
            // Normalize candidate paths to try matching against jos_admin_menus.menu_link
            $candidates = [];
            $candidates[] = basename(__FILE__); // e.g. otp_report.php
            if(!empty($_SERVER['SCRIPT_NAME'])) $candidates[] = $_SERVER['SCRIPT_NAME']; // e.g. /admin/otp_report.php
            if(!empty($_SERVER['PHP_SELF'])) $candidates[] = $_SERVER['PHP_SELF'];
            if(!empty($_SERVER['REQUEST_URI'])) {
                $reqPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
                if($reqPath) $candidates[] = $reqPath; // path without query
            }
            // Unique and non-empty
            $candidates = array_values(array_filter(array_unique($candidates)));

            // Try to find a menu entry that contains any of the candidates in menu_link
            $found = false;
            $sql = "SELECT id, title, menu_link FROM jos_admin_menus WHERE menu_link LIKE CONCAT('%', ?, '%') LIMIT 1";
            foreach($candidates as $cand) {
                if(!$cand) continue;
                $stmt = $con->prepare($sql);
                if($stmt) {
                    $stmt->bind_param('s', $cand);
                    $stmt->execute();
                    $stmt->bind_result($mid, $mtitle, $mlink);
                    if($stmt->fetch()) {
                        $res['menu_id'] = $mid;
                        $res['title'] = $mtitle ?: $res['title'];
                        $found = true;
                        $stmt->close();
                        break;
                    }
                    $stmt->close();
                }
            }

            // Fallback: try to match by a sensible title substring if no menu_link match found
            if(!$found) {
                $sql2 = "SELECT id, title FROM jos_admin_menus WHERE title LIKE '%OTP Report%' LIMIT 1";
                $stmt2 = $con->prepare($sql2);
                if($stmt2) {
                    $stmt2->execute();
                    $stmt2->bind_result($mid2, $mtitle2);
                    if($stmt2->fetch()) {
                        $res['menu_id'] = $mid2;
                        $res['title'] = $mtitle2 ?: $res['title'];
                    }
                    $stmt2->close();
                }
            }
        }

        // if we have a menu id, try to load permissions based on user's first role
        if($res['menu_id']) {
            $user_id = pacific_get_current_user_id();
            if($user_id) {
                // get role
                $qr = "SELECT role_id FROM jos_admin_users_roles WHERE user_id = ? LIMIT 1";
                $stmtR = $con->prepare($qr);
                if($stmtR) {
                    $stmtR->bind_param('i',$user_id);
                    $stmtR->execute();
                    $stmtR->bind_result($role_id);
                    if($stmtR->fetch()) {
                        $stmtR->close();
                        // now check rolemenus
                        $qperm = "SELECT can_view, can_add, can_edit, can_delete
                                  FROM jos_admin_rolemenus
                                  WHERE role_id = ? AND menu_id = ? LIMIT 1";
                        $stmtP = $con->prepare($qperm);
                        if($stmtP) {
                            $stmtP->bind_param('ii', $role_id, $res['menu_id']);
                            $stmtP->execute();
                            $stmtP->bind_result($pv, $pa, $pe, $pd);
                            if($stmtP->fetch()) {
                                $res['can_view']   = (bool)$pv;
                                $res['can_add']    = (bool)$pa;
                                $res['can_edit']   = (bool)$pe;
                                $res['can_delete'] = (bool)$pd;
                            }
                            $stmtP->close();
                        }
                    } else {
                        $stmtR->close();
                    }
                }
            }
        }

        return $res;
    }, $result);
}

/* ---------- load menu + permissions ---------- */
$menu_meta = pacific_get_menu_and_permissions($con);
$page_title = $menu_meta['title'] ?? 'OTP Report';
$CAN_VIEW   = !empty($menu_meta['can_view']);
$CAN_ADD    = !empty($menu_meta['can_add']);
$CAN_EDIT   = !empty($menu_meta['can_edit']);
$CAN_DELETE = !empty($menu_meta['can_delete']);

/* Enforce view permission immediately */
if(!$CAN_VIEW) {
    ob_start();
    echo '<link rel="stylesheet" href="/adminconsole/assets/ui.css">';
    echo '<div class="master-wrap"><div class="card">';
    echo '<div class="headbar"><h2 style="margin:0">'.htmlspecialchars($page_title).'</h2></div>';
    echo '<div class="alert danger">403 - Access denied. You do not have permission to view this page.</div>';
    echo '</div></div>';
    echo ob_get_clean();
    http_response_code(403);
    exit;
}

/* ---- existing code (preserved) ---- */
ob_start();
?>
<link rel="stylesheet" href="/adminconsole/assets/ui.css">
<div class="master-wrap">
  <div class="headbar">
    <h2 style="margin:0"><?=htmlspecialchars($page_title)?></h2>
    <div style="margin-left:auto">
      <?php
        // Back to list: check if a return URL is present, otherwise link to list with sane defaults
        $return_url = isset($_GET['return']) ? trim((string)$_GET['return']) : null;
        if($return_url){
            // ensure safe: only allow internal relative paths
            if(strpos($return_url, 'http://')===0 || strpos($return_url,'https://')===0) {
                $return_url = null;
            }
        }
        if(!$return_url) {
            // default back to this page root (no extra params)
            $return_url = strtok($_SERVER["REQUEST_URI"],'?'); // path only
        }
      ?>
      <?php if($CAN_ADD): ?>
        <a class="btn primary" href="<?=htmlspecialchars($return_url . (strpos($return_url, '?')!==false ? '&' : '?') . 'action=add&return=' . rawurlencode($_SERVER['REQUEST_URI']))?>">+ Add New</a>
      <?php endif; ?>
      <a class="btn secondary" href="<?=htmlspecialchars($return_url)?>">Back to List</a>
    </div>
  </div>
  <div class="card">
<?php
/* ---- helpers ---- */
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); return $q?('?'.$q):'';
}
function get_str($key,$default=''){ return isset($_GET[$key]) ? trim((string)$_GET[$key]) : $default; }

/* ---- filters ---- */
$mobile    = get_str('mobile','');
$purpose   = get_str('purpose','');
$from_date = get_str('from_date','');
$to_date   = get_str('to_date','');
$view      = get_str('view','last50'); // last50|all
$per_page  = ($view==='all') ? 1000 : 50;
$page      = max(1, (int)($_GET['page'] ?? 1));
$offset    = ($page-1)*$per_page;

/* ---- where clause ---- */
$where = []; $types=''; $params=[];
if($mobile!==''){ $where[]="mobile_number LIKE CONCAT('%',?,'%')"; $types.='s'; $params[]=$mobile; }
if($purpose!==''){ $where[]="purpose=?"; $types.='s'; $params[]=$purpose; }
if($from_date!==''){ $where[]="DATE(created_at)>=?"; $types.='s'; $params[]=$from_date; }
if($to_date!==''){ $where[]="DATE(created_at)<=?"; $types.='s'; $params[]=$to_date; }
$sql_where = $where ? ' WHERE '.implode(' AND ',$where) : '';

/* ---- total ---- */
$sql_count = "SELECT COUNT(*) FROM user_otp $sql_where";
$stmt = $con->prepare($sql_count);
if($stmt && $types!==''){ $stmt->bind_param($types, ...$params); }
if($stmt){ $stmt->execute(); $stmt->bind_result($total); $stmt->fetch(); $stmt->close(); }
else { $total = 0; }

/* protect page indices */
if(!isset($total) || $total===null) $total = 0;

if($view!=='all'){
  $pages = max(1, ceil($total/$per_page));
  if($page>$pages){ $page=$pages; $offset=($page-1)*$per_page; }
} else { $pages=1; $page=1; $offset=0; }

/* ---- main query ---- */
$sql = "SELECT id,mobile_number,otp_code,status,purpose,created_at,verified_at 
        FROM user_otp $sql_where 
        ORDER BY created_at DESC 
        ".($view==='all' ? "" : " LIMIT $per_page OFFSET $offset");
$stmt = $con->prepare($sql);
if($stmt && $types!==''){ $stmt->bind_param($types, ...$params); }
if($stmt){ $stmt->execute(); $res = $stmt->get_result(); }
else { $res = new class {
    public $num_rows = 0;
    public function fetch_assoc(){ return false; }
}; }

/* ---- filters UI ---- */
?>
<form method="get" class="toolbar" style="gap:10px;flex-wrap:wrap">
  <input class="inp" type="text" name="mobile" value="<?=h($mobile)?>" placeholder="Mobile Number">
  <select class="inp" name="purpose">
    <option value="" <?= $purpose===''?'selected':''?>>All Purposes</option>
    <option value="signup" <?= $purpose==='signup'?'selected':''?>>Signup</option>
    <option value="forgot_password" <?= $purpose==='forgot_password'?'selected':''?>>Forgot Password</option>
  </select>
  <input class="inp" type="date" name="from_date" value="<?=h($from_date)?>">
  <input class="inp" type="date" name="to_date" value="<?=h($to_date)?>">
  <button class="btn primary" type="submit">Apply</button>

  <div style="flex:1"></div>
  <a class="btn secondary" href="<?=h(keep_params(['view'=>'last50','page'=>1]))?>">Last 50</a>
  <a class="btn secondary" href="<?=h(keep_params(['view'=>'all','page'=>1]))?>">View All</a>
</form>

<div style="display:flex;align-items:center;gap:12px;margin:8px 0 12px">
  <span class="badge">Total: <?=$total?></span>
  <span class="badge">Showing: <?=$res->num_rows?></span>
</div>

<div class="table-wrap">
<table class="table">
  <thead>
    <tr>
      <th>SR No</th>
      <th>Mobile Number</th>
      <th>OTP Code</th>
      <th>Status</th>
      <th>Purpose</th>
      <th>Created At</th>
      <th>Verified At</th>
      <?php if($CAN_EDIT || $CAN_DELETE): ?><th>Actions</th><?php endif; ?>
    </tr>
  </thead>
  <tbody>
<?php
$sr = ($view==='all')?1:($offset+1);
while($row = $res->fetch_assoc()):
  $status_badge = ($row['status']==='verified')
    ? '<span class="badge success">Verified</span>'
    : '<span class="badge warn">'.h($row['status']).'</span>';

  $created_fmt  = $row['created_at'] ? date('d-m-Y H:i:s', strtotime($row['created_at'])) : '—';
  $verified_fmt = $row['verified_at'] ? date('d-m-Y H:i:s', strtotime($row['verified_at'])) : '—';
?>
    <tr>
      <td><?=$sr++?></td>
      <td><?=h($row['mobile_number'])?></td>
      <td><?=h($row['otp_code'])?></td>
      <td><?=$status_badge?></td>
      <td><?=h($row['purpose'])?></td>
      <td><?=$created_fmt?></td>
      <td><?=$verified_fmt?></td>
      <?php if($CAN_EDIT || $CAN_DELETE): ?>
      <td>
        <?php if($CAN_EDIT): ?>
          <a class="btn small" href="<?=h(keep_params(['action'=>'edit','id'=>$row['id'],'return'=>rawurlencode($_SERVER['REQUEST_URI'])]))?>">Edit</a>
        <?php endif; ?>
        <?php if($CAN_DELETE): ?>
          <a class="btn small danger" href="<?=h(keep_params(['action'=>'delete','id'=>$row['id'],'confirm'=>1,'return'=>rawurlencode($_SERVER['REQUEST_URI'])]))?>" onclick="return confirm('Delete this OTP record?');">Delete</a>
        <?php endif; ?>
      </td>
      <?php endif; ?>
    </tr>
<?php endwhile; if(isset($stmt)) $stmt->close(); ?>
<?php if($sr===($view==='all'?1:$offset+1)): ?>
    <tr><td colspan="<?= $CAN_EDIT||$CAN_DELETE ? 8 : 7 ?>" style="text-align:center;color:#9ca3af">No records found.</td></tr>
<?php endif; ?>
  </tbody>
</table>
</div>

<?php if($view!=='all'){ ?>
<div style="display:flex;gap:8px;justify-content:flex-end;margin-top:12px">
  <?php if($page>1){ ?><a class="btn secondary" href="<?=h(keep_params(['page'=>$page-1]))?>">‹ Prev</a><?php } ?>
  <span class="badge">Page <?= (int)$page ?> / <?= (int)$pages ?></span>
  <?php if($page<$pages){ ?><a class="btn secondary" href="<?=h(keep_params(['page'=>$page+1]))?>">Next ›</a><?php } ?>
</div>
<?php } ?>

  </div>
</div>
<?php
echo ob_get_clean();  
