<?php
// admin_bvn_phone.php
// Admin panel for BVN-by-phone results: edit price, edit reply/status, upload PDF slip, delete, download.
// Requirements:
// - session_start(); $_SESSION['admin'] must be set (admin email/name).
// - db.php must set $conn (mysqli).
// - Table: bvn_phone_price (id, standard_price, premium_price) — created previously.
// - Table: bvn_results with at least these columns:
//   id INT AUTO_INCREMENT PRIMARY KEY,
//   email VARCHAR(255),        -- user who requested (optional)
//   phone VARCHAR(32),        -- searched phone
//   bvn VARCHAR(20),
//   first_name VARCHAR(120),
//   last_name VARCHAR(120),
//   dob VARCHAR(30),
//   slip_type VARCHAR(20) DEFAULT 'standard', -- 'standard'|'premium'
//   status VARCHAR(32) DEFAULT 'pending',
//   reply TEXT,
//   pdf_file VARCHAR(255),    -- stored filename under uploads/bvn_phone/
//   price DOUBLE DEFAULT 0,
//   created_at DATETIME DEFAULT CURRENT_TIMESTAMP

ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();
if (!isset($_SESSION['admin'])) {
    header('Location: admin_login.php');
    exit;
}

// adjust path to your db.php as needed
require_once __DIR__ . '/../db.php';
if (!isset($conn) || !($conn instanceof mysqli)) {
    die("Database connection missing. Ensure db.php creates \$conn (mysqli).");
}

// Upload dir for PDFs
$UPLOAD_DIR = __DIR__ . '/../uploads/bvn_phone/';
if (!is_dir($UPLOAD_DIR)) @mkdir($UPLOAD_DIR, 0775, true);

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

// ----------------
// Handle AJAX POST actions
// ----------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_action'])) {
    header('Content-Type: application/json; charset=utf-8');
    $action = $_POST['ajax_action'];

    // update prices
    if ($action === 'update_prices') {
        $std = floatval($_POST['standard_price'] ?? 0);
        $prem = floatval($_POST['premium_price'] ?? 0);

        // upsert
        $q = $conn->query("SELECT id FROM bvn_phone_price LIMIT 1");
        if ($q && $q->num_rows > 0) {
            $stmt = $conn->prepare("UPDATE bvn_phone_price SET standard_price = ?, premium_price = ? LIMIT 1");
            $stmt->bind_param("dd", $std, $prem);
            $ok = $stmt->execute();
            $stmt->close();
        } else {
            $stmt = $conn->prepare("INSERT INTO bvn_phone_price (standard_price, premium_price) VALUES (?, ?)");
            $stmt->bind_param("dd", $std, $prem);
            $ok = $stmt->execute();
            $stmt->close();
        }
        echo json_encode(['success' => (bool)$ok, 'standard_price' => number_format($std,2,'.',''), 'premium_price' => number_format($prem,2,'.','')]);
        exit;
    }

    // edit a result: status, reply and optional PDF upload
    if ($action === 'edit_result') {
        $id = intval($_POST['id'] ?? 0);
        if ($id <= 0) { echo json_encode(['success'=>false,'msg'=>'Invalid id']); exit; }

        $status = trim($_POST['status'] ?? 'pending');
        $reply  = trim($_POST['reply'] ?? '');

        // sanitize allowed statuses
        $allowed = ['pending','in-progress','successful','failed'];
        if (!in_array($status, $allowed, true)) $status = 'pending';

        // handle optional file upload (ajax multipart must be used)
        $pdf_filename = null;
        if (!empty($_FILES['pdf_file']) && $_FILES['pdf_file']['error'] === UPLOAD_ERR_OK) {
            $tmp = $_FILES['pdf_file']['tmp_name'];
            $orig = basename($_FILES['pdf_file']['name']);
            $ext = pathinfo($orig, PATHINFO_EXTENSION);
            $ext = preg_replace("/[^a-zA-Z0-9]/", '', $ext);
            if ($ext === '') $ext = 'pdf';
            $safe = 'bvn_pdf_' . time() . '_' . bin2hex(random_bytes(6)) . '.' . $ext;
            $dest = rtrim($UPLOAD_DIR, '/\\') . DIRECTORY_SEPARATOR . $safe;
            if (!move_uploaded_file($tmp, $dest)) {
                echo json_encode(['success'=>false,'msg'=>'Failed to move uploaded file']); exit;
            }
            $pdf_filename = $safe;
        }

        // Build update SQL
        if ($pdf_filename !== null) {
            $stmt = $conn->prepare("UPDATE bvn_results SET status = ?, reply = ?, pdf_file = ? WHERE id = ?");
            $stmt->bind_param("sssi", $status, $reply, $pdf_filename, $id);
        } else {
            $stmt = $conn->prepare("UPDATE bvn_results SET status = ?, reply = ? WHERE id = ?");
            $stmt->bind_param("ssi", $status, $reply, $id);
        }
        $ok = $stmt->execute();
        $err = $stmt->error;
        $stmt->close();
        echo json_encode(['success' => (bool)$ok, 'error'=>$err]);
        exit;
    }

    // delete record
    if ($action === 'delete') {
        $id = intval($_POST['id'] ?? 0);
        if ($id <= 0) { echo json_encode(['success'=>false,'msg'=>'Invalid id']); exit; }
        // remove attached PDF if any
        $s = $conn->prepare("SELECT pdf_file FROM bvn_results WHERE id = ? LIMIT 1");
        $s->bind_param("i",$id); $s->execute(); $rr = $s->get_result()->fetch_assoc(); $s->close();
        if ($rr && !empty($rr['pdf_file'])) {
            $path = $UPLOAD_DIR . $rr['pdf_file'];
            if (file_exists($path)) @unlink($path);
        }
        $d = $conn->prepare("DELETE FROM bvn_results WHERE id = ?");
        $d->bind_param("i",$id);
        $ok = $d->execute();
        $d->close();
        echo json_encode(['success'=> (bool)$ok]);
        exit;
    }

    echo json_encode(['success'=>false,'msg'=>'Unknown action']);
    exit;
}

// ----------------
// Page (GET)
// ----------------
// load prices
$std_price = 0.00; $prem_price = 0.00;
$q = $conn->query("SELECT standard_price, premium_price FROM bvn_phone_price LIMIT 1");
if ($q && ($row = $q->fetch_assoc())) {
    $std_price = floatval($row['standard_price']);
    $prem_price = floatval($row['premium_price']);
}

// filters & pagination
$q_search = trim($_GET['q'] ?? '');
$filter_status = trim($_GET['status'] ?? '');
$page = max(1, intval($_GET['page'] ?? 1));
$per_page = 40;
$offset = ($page -1) * $per_page;

// count total
$count_sql = "SELECT COUNT(*) AS cnt FROM bvn_results WHERE 1=1";
$params = []; $types = "";
if ($q_search !== '') { $count_sql .= " AND (phone LIKE ? OR bvn LIKE ? OR first_name LIKE ? OR last_name LIKE ?)"; $params[] = "%$q_search%"; $params[] = "%$q_search%"; $params[] = "%$q_search%"; $params[] = "%$q_search%"; $types .= "ssss"; }
if ($filter_status !== '') { $count_sql .= " AND status = ?"; $params[] = $filter_status; $types .= "s"; }
$stmtC = $conn->prepare($count_sql);
if ($params) {
    $refs = []; foreach ($params as $k=>$v) $refs[$k] = &$params[$k];
    array_unshift($refs, $types);
    call_user_func_array([$stmtC, 'bind_param'], $refs);
}
$stmtC->execute();
$totalCnt = $stmtC->get_result()->fetch_assoc()['cnt'] ?? 0;
$stmtC->close();
$total_pages = max(1, ceil($totalCnt / $per_page));

// select rows
$list_sql = "SELECT id, email, phone, bvn, first_name, last_name, dob, slip_type, status, reply, pdf_file, price, created_at
             FROM bvn_results WHERE 1=1";
if ($q_search !== '') $list_sql .= " AND (phone LIKE ? OR bvn LIKE ? OR first_name LIKE ? OR last_name LIKE ?)";
if ($filter_status !== '') $list_sql .= " AND status = ?";
$list_sql .= " ORDER BY id DESC LIMIT ? OFFSET ?";

$stmt = $conn->prepare($list_sql);

$bind_params = [];
$bind_types = "";
if ($q_search !== '') { $bind_types .= "ssss"; $bind_params[] = "%$q_search%"; $bind_params[] = "%$q_search%"; $bind_params[] = "%$q_search%"; $bind_params[] = "%$q_search%"; }
if ($filter_status !== '') { $bind_types .= "s"; $bind_params[] = $filter_status; }
$bind_types .= "ii"; $bind_params[] = $per_page; $bind_params[] = $offset;

$refs = [];
foreach ($bind_params as $k=>$v) $refs[$k] = &$bind_params[$k];
array_unshift($refs, $bind_types);
call_user_func_array([$stmt, 'bind_param'], $refs);
$stmt->execute();
$result = $stmt->get_result();

?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Admin — BVN by Phone</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<style>
:root{--bg:#071427;--card:#07233d;--accent:#00d5ff;--muted:#cfe8ff}
*{box-sizing:border-box;margin:0;padding:0;font-family:Inter,Arial,sans-serif}
body{min-height:100vh;background:var(--bg);color:var(--muted);padding:18px}
.container{max-width:1200px;margin:0 auto}
.header{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px}
.logo{width:44px;height:44px;border-radius:8px;background:var(--accent);display:flex;align-items:center;justify-content:center;color:#012;font-weight:800}
.card{background:var(--card);padding:14px;border-radius:12px;margin-bottom:12px}
input,select,textarea{padding:8px;border-radius:8px;border:1px solid rgba(255,255,255,0.04);background:transparent;color:var(--muted)}
button{padding:8px 12px;border-radius:8px;border:0;background:var(--accent);color:#012;cursor:pointer}
.table{width:100%;border-collapse:collapse;margin-top:12px}
.table th,.table td{padding:10px;border-bottom:1px solid rgba(255,255,255,0.03);text-align:left;vertical-align:middle}
.small{font-size:13px;color:#bfe9ff}
.status.pending{color:#60a5fa;font-weight:700}
.status.in-progress{color:#f59e0b;font-weight:700}
.status.successful{color:#22c55e;font-weight:700}
.status.failed{color:#ef4444;font-weight:700}
.link{color:var(--accent);text-decoration:none;font-weight:700}
.badge{padding:6px 8px;border-radius:6px;background:rgba(255,255,255,0.03)}
.pagination{display:flex;gap:8px;align-items:center;margin-top:10px}
.file-link{color:#fff;text-decoration:underline}
.form-row{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
</style>
</head>
<body>
<div class="container">
  <div class="header">
    <div style="display:flex;gap:12px;align-items:center">
      <div class="logo">AS</div>
      <div>
        <h2 style="margin:0">Admin — BVN by Phone</h2>
        <div class="small">Manage BVN phone lookups, edit reply/status, upload slip PDF, change prices</div>
      </div>
    </div>
    <div style="text-align:right">
      <div class="small">Admin: <?= h($_SESSION['admin']) ?></div>
    </div>
  </div>

  <div class="card">
    <form id="filterForm" method="GET" style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
      <input type="text" name="q" placeholder="Search phone / bvn / name" value="<?= h($q_search) ?>" style="width:320px">
      <select name="status">
        <option value="">All statuses</option>
        <option value="pending" <?= $filter_status==='pending'?'selected':'' ?>>Pending</option>
        <option value="in-progress" <?= $filter_status==='in-progress'?'selected':'' ?>>In-Progress</option>
        <option value="successful" <?= $filter_status==='successful'?'selected':'' ?>>Successful</option>
        <option value="failed" <?= $filter_status==='failed'?'selected':'' ?>>Failed</option>
      </select>
      <button type="submit">Filter</button>

      <div style="margin-left:auto;display:flex;gap:8px;align-items:center">
        <label class="small">Standard: ₦</label>
        <input id="standard_price" type="number" step="0.01" value="<?= number_format($std_price,2,'.','') ?>" style="width:110px">
        <label class="small">Premium: ₦</label>
        <input id="premium_price" type="number" step="0.01" value="<?= number_format($prem_price,2,'.','') ?>" style="width:110px">
        <button id="savePricesBtn" type="button">Save Prices</button>
      </div>
    </form>
  </div>

  <div class="card">
    <div class="small">Showing page <?= $page ?> of <?= $total_pages ?> (<?= $totalCnt ?> total)</div>

    <table class="table">
      <thead>
        <tr>
          <th>ID</th><th>Phone</th><th>BVN</th><th>Name</th><th>DOB</th><th>Slip</th><th>Status</th><th>Price</th><th>PDF</th><th>Reply</th><th>Created</th><th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php while ($r = $result->fetch_assoc()): ?>
          <tr id="row-<?= (int)$r['id'] ?>">
            <td><?= (int)$r['id'] ?></td>
            <td><?= h($r['phone'] ?? '') ?></td>
            <td><?= h($r['bvn'] ?? '') ?></td>
            <td><?= h(trim(($r['first_name'] ?? '') . ' ' . ($r['last_name'] ?? ''))) ?></td>
            <td><?= h($r['dob'] ?? '') ?></td>
            <td><?= h($r['slip_type'] ?? 'standard') ?></td>
            <td><span class="status <?= h(strtolower($r['status'] ?? 'pending')) ?>"><?= h($r['status']) ?></span></td>
            <td>₦<?= number_format(floatval($r['price'] ?? 0),2) ?></td>
            <td>
              <?php if (!empty($r['pdf_file'])): ?>
                <a class="file-link" href="<?= h('../uploads/bvn_phone/' . $r['pdf_file']) ?>" target="_blank">View PDF</a>
              <?php else: ?>-<?php endif; ?>
            </td>
            <td style="max-width:240px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"><?= h($r['reply'] ?: '-') ?></td>
            <td><?= h($r['created_at']) ?></td>
            <td style="white-space:nowrap">
              <button onclick="openEdit(<?= (int)$r['id'] ?>)"><i class="fa fa-edit"></i></button>
              <button onclick="doDelete(<?= (int)$r['id'] ?>)" style="background:#ff5c5c;color:#fff"><i class="fa fa-trash"></i></button>
            </td>
          </tr>
        <?php endwhile; ?>
      </tbody>
    </table>

    <div class="pagination">
      <?php if($page>1): ?>
        <a href="?<?= http_build_query(array_merge($_GET,['page'=>$page-1])) ?>" class="small">Prev</a>
      <?php endif; ?>
      <div class="small">Page <?= $page ?> / <?= $total_pages ?></div>
      <?php if($page < $total_pages): ?>
        <a href="?<?= http_build_query(array_merge($_GET,['page'=>$page+1])) ?>" class="small">Next</a>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- Edit Modal -->
<div id="modal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.6);align-items:center;justify-content:center">
  <div style="background:var(--card);padding:16px;border-radius:10px;width:95%;max-width:820px;color:var(--muted)">
    <h3 style="margin-top:0">Edit Result</h3>
    <form id="editForm" enctype="multipart/form-data">
      <input type="hidden" name="id" id="edit_id" value="">
      <div class="form-row" style="margin-bottom:8px">
        <label class="small">Status</label>
        <select name="status" id="edit_status">
          <option value="pending">Pending</option>
          <option value="in-progress">In-Progress</option>
          <option value="successful">Successful</option>
          <option value="failed">Failed</option>
        </select>

        <label class="small">Slip Type</label>
        <select id="edit_slip_type" name="slip_type">
          <option value="standard">Standard</option>
          <option value="premium">Premium</option>
        </select>

        <label class="small">Price</label>
        <input type="number" step="0.01" id="edit_price" name="price" style="width:140px">
      </div>

      <div style="margin-bottom:8px">
        <label class="small">Reply (visible to user)</label>
        <textarea id="edit_reply" name="reply" style="width:100%;min-height:120px"></textarea>
      </div>

      <div style="margin-bottom:8px">
        <label class="small">Upload Slip PDF (optional)</label>
        <input type="file" name="pdf_file" accept="application/pdf">
      </div>

      <div style="display:flex;gap:8px;justify-content:flex-end">
        <button type="button" onclick="closeModal()" style="background:#666;color:#fff">Cancel</button>
        <button type="button" id="saveEditBtn">Save</button>
      </div>
    </form>
  </div>
</div>

<script>
const adminEndpoint = location.pathname;
function doDelete(id){
  if(!confirm('Delete record #' + id + ' ?')) return;
  const fd = new FormData();
  fd.append('ajax_action','delete');
  fd.append('id', id);
  fetch(adminEndpoint, {method:'POST', body: fd})
    .then(r=>r.json()).then(d=>{
      if (d.success) {
        const tr = document.getElementById('row-' + id);
        if (tr) tr.remove();
        alert('Deleted');
      } else alert('Delete failed');
    }).catch(e=>{console.error(e); alert('Network error')});
}

// Save prices
document.getElementById('savePricesBtn').addEventListener('click', ()=>{
  const std = document.getElementById('standard_price').value;
  const prem = document.getElementById('premium_price').value;
  const fd = new FormData();
  fd.append('ajax_action','update_prices');
  fd.append('standard_price', std);
  fd.append('premium_price', prem);
  fetch(adminEndpoint, {method:'POST', body: fd})
    .then(r=>r.json()).then(d=>{
      if (d.success) alert('Prices updated');
      else alert('Failed to update prices');
    }).catch(e=>{console.error(e); alert('Network error')});
});

function openEdit(id){
  // pull row data from DOM (we have limited columns); for robust data fetch, implement an endpoint to fetch record by id
  const row = document.getElementById('row-' + id);
  if (!row) return;
  const tds = row.getElementsByTagName('td');
  document.getElementById('edit_id').value = id;
  // status is in td[6]
  const statusText = row.querySelector('.status') ? row.querySelector('.status').textContent.trim().toLowerCase() : 'pending';
  document.getElementById('edit_status').value = statusText;
  // slip type in td[5]
  document.getElementById('edit_slip_type').value = tds[5].textContent.trim();
  // price in td[7] (₦xxx)
  const priceText = tds[7].textContent.replace('₦','').replace(',','').trim();
  document.getElementById('edit_price').value = priceText ? parseFloat(priceText) : '';
  // reply in td[9]
  document.getElementById('edit_reply').value = tds[9].textContent.trim() === '-' ? '' : tds[9].textContent.trim();
  document.getElementById('modal').style.display = 'flex';
}

function closeModal(){
  document.getElementById('modal').style.display = 'none';
}

document.getElementById('saveEditBtn').addEventListener('click', ()=> {
  const form = document.getElementById('editForm');
  const fd = new FormData(form);
  fd.append('ajax_action','edit_result');
  // include slip_type and price into reply update as well (server can handle if you store them)
  fetch(adminEndpoint, { method: 'POST', body: fd })
    .then(r=>r.json()).then(d=>{
      if (d.success) {
        alert('Saved');
        location.reload();
      } else {
        alert('Save failed: ' + (d.msg || d.error || 'unknown'));
      }
    }).catch(e=>{console.error(e); alert('Network error')});
});
</script>
</body>
</html>