<?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;
    }
    function normalize_filter_date($date)
    {
      $date = trim((string)$date);
      if ($date === '') return '';
      foreach (['Y-m-d', 'd-m-Y', 'd/m/Y'] as $fmt) {
        $d = DateTime::createFromFormat($fmt, $date);
        if ($d) return $d->format('Y-m-d');
      }
      return '';
    }

    /* Superadmin dashboard POST support: convert dashboard card submits into persistent GET filters. */
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['range']) || isset($_POST['from']) || isset($_POST['to']) || isset($_POST['mobile']) || isset($_POST['purpose']))) {
      $range = trim((string)($_POST['range'] ?? ''));
      $from = normalize_filter_date($_POST['from'] ?? '');
      $to = normalize_filter_date($_POST['to'] ?? '');

      if ($range === 'daily') {
        $from = date('Y-m-d');
        $to = date('Y-m-d');
      } elseif ($range === 'weekly') {
        $today = (int)date('w');
        $from = date('Y-m-d', strtotime('-' . $today . ' days'));
        $to = date('Y-m-d', strtotime('+' . (6 - $today) . ' days'));
      } elseif ($range === 'monthly') {
        $from = date('Y-m-01');
        $to = date('Y-m-d');
      } elseif ($range === 'lifetime') {
        $from = '';
        $to = '';
      }

      $qs = ['source' => 'superadmin'];
      if (isset($_POST['menu_id']) && is_numeric($_POST['menu_id'])) $qs['menu_id'] = (int)$_POST['menu_id'];
      if (trim((string)($_POST['mobile'] ?? '')) !== '') $qs['mobile'] = trim((string)$_POST['mobile']);
      if (trim((string)($_POST['purpose'] ?? '')) !== '') $qs['purpose'] = trim((string)$_POST['purpose']);
      if ($from !== '') $qs['from_date'] = $from;
      if ($to !== '') $qs['to_date'] = $to;

      header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?') . '?' . http_build_query($qs));
      exit;
    }

    /* ---- filters ---- */
    $is_superadmin_source = (get_str('source', '') === 'superadmin');
    $mobile    = get_str('mobile', '');
    $purpose   = get_str('purpose', '');
    $single_date = normalize_filter_date(get_str('date', ''));
    $from_date = normalize_filter_date(get_str('from_date', get_str('from', $single_date)));
    $to_date   = normalize_filter_date(get_str('to_date', get_str('to', $single_date)));
    $view      = $is_superadmin_source ? 'all' : 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 ---- */
    ?>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <style>
      .otp-toolbar {
        display: flex;
        gap: 12px;
        flex-wrap: wrap;
        align-items: end;
      }

      .otp-toolbar .group {
        display: flex;
        flex-direction: column;
        min-width: 160px;
      }

      .otp-toolbar .group label {
        color: #9ca3af;
        font-size: 12px;
        margin-bottom: 5px;
      }

      .date-field {
        position: relative;
      }

      .date-field .inp {
        padding-right: 34px;
      }

      .date-field .cal-icon {
        position: absolute;
        right: 10px;
        bottom: 9px;
        color: #9ca3af;
        pointer-events: none;
        font-size: 14px;
      }
    </style>
    <form method="get" class="toolbar otp-toolbar">
      <?php if ($is_superadmin_source): ?>
        <input type="hidden" name="source" value="superadmin">
      <?php endif; ?>
      <?php if (isset($_GET['menu_id'])): ?>
        <input type="hidden" name="menu_id" value="<?= h((string)$_GET['menu_id']) ?>">
      <?php endif; ?>

      <div class="group">
        <label>Mobile</label>
        <input class="inp" type="text" name="mobile" value="<?= h($mobile) ?>" placeholder="Mobile Number">
      </div>

      <div class="group">
        <label>Purpose</label>
        <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>
      </div>

      <div class="group date-field">
        <label>From Date</label>
        <input class="inp flatpickr" type="text" name="from_date" value="<?= h($from_date) ?>" placeholder="DD-MM-YYYY">
        <span class="cal-icon">▦</span>
      </div>

      <div class="group date-field">
        <label>To Date</label>
        <input class="inp flatpickr" type="text" name="to_date" value="<?= h($to_date) ?>" placeholder="DD-MM-YYYY">
        <span class="cal-icon">▦</span>
      </div>

      <?php if (!$is_superadmin_source): ?>
        <input type="hidden" name="view" value="<?= h($view) ?>">
      <?php endif; ?>

      <div class="group" style="min-width:auto">
        <label>&nbsp;</label>
        <button class="btn primary" type="submit">Apply</button>
      </div>

      <div class="group" style="min-width:auto">
        <label>&nbsp;</label>
        <a class="btn secondary" href="<?= h(keep_params(['mobile' => null, 'purpose' => null, 'from_date' => null, 'to_date' => null, 'from' => null, 'to' => null, 'page' => null])) ?>">Reset Filter</a>
      </div>

      <div style="flex:1"></div>
      <?php if (!$is_superadmin_source): ?>
        <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>
      <?php endif; ?>
    </form>
    <script>
           flatpickr('.flatpickr', {
          altInput: true,
          altFormat: 'd-m-Y',
          dateFormat: 'Y-m-d',
          allowInput: false
        });
  
    </script>

    <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();
