<?php
include('../includes/session.php');
include('../includes/config.php');

if (isset($_GET['action']) && $_GET['action'] == 'update' && isset($_GET['orderid'])) {
    header('Content-Type: application/json');
    $order_id = mysqli_real_escape_string($tng_conn, $_GET['orderid']);
    $api_key = "75be25-7dd29-00d56-648c1e-7c9127-1c39"; 

    $url = "https://dashbood.brotool.online/api/pan_find/aadhar_to_pan_find_status.php?api_key=$api_key&api_orderid=$order_id";
    $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $res = curl_exec($ch); curl_close($ch);
    $api_res = json_decode($res, true);
    
    if (isset($api_res['live_status'])) {
        $l_status = $api_res['live_status']; 
        $pan_val = $api_res['pan_number'] ?? '';
        $remark = mysqli_real_escape_string($tng_conn, $api_res['responce'] ?? 'Processed');

        $check_db = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT status, username FROM pan_find_requests WHERE order_id='$order_id'"));
        
        if($check_db['status'] == 'Pending') {
            if ($l_status == 'Successfully' || $l_status == 'Success') {
                mysqli_query($tng_conn, "UPDATE pan_find_requests SET status = 'Success', pan_card_no = '$pan_val', admin_remark = '$remark' WHERE order_id = '$order_id'");
                echo json_encode(['status' => 'success', 'msg' => $remark, 'pan' => $pan_val]);
            } 
            elseif ($l_status == 'Rejected') {
                $user_phone = $check_db['username'];
                $fee_refund = floatval($udata['tng_pan_panfind']);
                mysqli_begin_transaction($tng_conn);
                try {
                    mysqli_query($tng_conn, "UPDATE pan_find_requests SET status = 'Rejected', pan_card_no = 'REJECTED', admin_remark = '$remark' WHERE order_id = '$order_id'");
                    mysqli_query($tng_conn, "UPDATE users SET balance = balance + $fee_refund WHERE phone='$user_phone'");
                    mysqli_query($tng_conn, "INSERT INTO wallethistory (userid, amount, purpose, status, type) VALUES ('$user_phone', '$fee_refund', 'Refund: PAN Find Rejected', '1', 'Credit')");
                    mysqli_commit($tng_conn);
                    echo json_encode(['status' => 'error', 'msg' => 'Rejected: ' . $remark]);
                } catch (Exception $e) { mysqli_rollback($tng_conn); }
            } else {
                echo json_encode(['status' => 'info', 'msg' => $remark]);
            }
        } else { echo json_encode(['status' => 'info', 'msg' => 'Already Updated']); }
    }
    exit;
}

include('../template/tngweb/header.php'); 

$current_user = $udata['phone'];
$is_admin = ($udata['type'] == 'admin');

if ($is_admin) {
    $query = "SELECT * FROM pan_find_requests ORDER BY id DESC";
    $page_title = "PAN Find — All Users";
} else {
    $query = "SELECT * FROM pan_find_requests WHERE username='$current_user' ORDER BY id DESC";
    $page_title = "My PAN Find History";
}

$res = mysqli_query($tng_conn, $query);

/* Counts */
$all_res = mysqli_query($tng_conn, $is_admin
    ? "SELECT status, COUNT(*) c FROM pan_find_requests GROUP BY status"
    : "SELECT status, COUNT(*) c FROM pan_find_requests WHERE username='$current_user' GROUP BY status");
$counts = ['Pending'=>0,'Success'=>0,'Rejected'=>0,'Total'=>0];
while($cr = mysqli_fetch_assoc($all_res)){
    $counts[$cr['status']] = $cr['c'];
    $counts['Total'] += $cr['c'];
}
?>

<link href="https://fonts.googleapis.com/css2?family=Sora:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
:root{
  --br:#2563eb;--bg:#f0f4ff;--sur:#fff;--sur2:#f8faff;--bdr:#e2e8f8;
  --tx:#0f172a;--mu:#64748b;--ff:'Sora',sans-serif;
}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0;}
.lp{padding:20px 14px 50px;
  background:radial-gradient(ellipse 90% 35% at 50% 0%,rgba(37,99,235,.10),transparent 60%),var(--bg);
  min-height:100vh;}
.stats{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:18px;}
.sc{background:var(--sur);border:1px solid var(--bdr);border-radius:14px;padding:12px 14px;
  display:flex;align-items:center;gap:10px;box-shadow:0 2px 10px rgba(0,0,0,.04);
  animation:su .4s cubic-bezier(.22,1,.36,1) both;}
.sc:nth-child(1){animation-delay:.04s}.sc:nth-child(2){animation-delay:.08s}
.sc:nth-child(3){animation-delay:.12s}.sc:nth-child(4){animation-delay:.16s}
@keyframes su{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:translateY(0)}}
.sc-ico{width:36px;height:36px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0;}
.sc-all .sc-ico{background:rgba(37,99,235,.1);}
.sc-ok  .sc-ico{background:rgba(16,185,129,.1);}
.sc-pend .sc-ico{background:rgba(245,158,11,.1);}
.sc-rej .sc-ico{background:rgba(239,68,68,.1);}
.sc-num{font-size:22px;font-weight:800;color:var(--tx);line-height:1;}
.sc-lbl{font-size:10px;color:var(--mu);font-weight:500;margin-top:2px;}
.acard{background:var(--sur);border-radius:16px;
  box-shadow:0 12px 40px rgba(37,99,235,.09),0 2px 8px rgba(0,0,0,.04);
  border:1px solid var(--bdr);overflow:hidden;
  animation:su .4s .2s cubic-bezier(.22,1,.36,1) both;}
.acard-head{background:linear-gradient(135deg,#1e3a8a,#2563eb 55%,#0891b2);
  padding:16px 20px;display:flex;justify-content:space-between;align-items:center;
  flex-wrap:wrap;gap:10px;position:relative;overflow:hidden;}
.acard-head::before{content:'';position:absolute;top:-30px;right:-30px;width:110px;height:110px;border-radius:50%;background:rgba(255,255,255,.07);}
.acard-head h5{color:#fff;font-size:16px;font-weight:800;margin:0;position:relative;z-index:1;}
.acard-head p{color:rgba(255,255,255,.65);font-size:11.5px;margin:2px 0 0;position:relative;z-index:1;}
.new-btn{display:inline-flex;align-items:center;gap:6px;background:rgba(255,255,255,.18);
  border:1px solid rgba(255,255,255,.3);color:#fff;font-size:12.5px;font-weight:700;
  padding:7px 16px;border-radius:10px;text-decoration:none;transition:.18s;position:relative;z-index:1;}
.new-btn:hover{background:rgba(255,255,255,.28);color:#fff;}
.tscroll{overflow-x:auto;}
table{width:100%;border-collapse:collapse;font-family:var(--ff);font-size:13px;}
thead tr{background:var(--sur2);border-bottom:2px solid var(--bdr);}
thead th{padding:11px 13px;font-weight:700;color:var(--mu);text-transform:uppercase;font-size:10px;letter-spacing:.7px;white-space:nowrap;}
tbody tr{border-bottom:1px solid #f1f5fb;transition:.15s;}
tbody tr:hover{background:#f5f8ff;}
tbody td{padding:12px 13px;color:var(--tx);vertical-align:middle;}
.aadhar-chip{display:inline-flex;align-items:center;gap:5px;background:rgba(37,99,235,.07);
  border:1px solid rgba(37,99,235,.15);padding:3px 9px;border-radius:7px;font-size:12px;font-weight:700;color:#1d4ed8;}
.uid-chip{font-size:11.5px;color:var(--mu);background:var(--sur2);border:1px solid var(--bdr);padding:2px 8px;border-radius:6px;}
.pan-result{display:inline-flex;align-items:center;gap:6px;background:rgba(16,185,129,.07);
  border:1px solid rgba(16,185,129,.2);padding:5px 12px;border-radius:8px;
  font-size:13px;font-weight:800;color:#065f46;letter-spacing:.5px;}
.copy-btn{background:none;border:none;cursor:pointer;font-size:14px;padding:2px 4px;transition:.15s;}
.copy-btn:hover{transform:scale(1.2);}
.badge{display:inline-flex;align-items:center;gap:4px;padding:4px 10px;border-radius:20px;font-size:11px;font-weight:700;white-space:nowrap;}
.b-ok{background:rgba(16,185,129,.1);color:#059669;border:1px solid rgba(16,185,129,.2);}
.b-pend{background:rgba(245,158,11,.1);color:#d97706;border:1px solid rgba(245,158,11,.2);}
.b-rej{background:rgba(239,68,68,.1);color:#dc2626;border:1px solid rgba(239,68,68,.2);}
.btn-chk{display:inline-flex;align-items:center;gap:4px;padding:6px 13px;border-radius:8px;border:none;cursor:pointer;
  font-size:12px;font-weight:700;font-family:var(--ff);
  background:linear-gradient(135deg,#1d4ed8,#2563eb);color:#fff;
  box-shadow:0 2px 8px rgba(37,99,235,.25);transition:.18s;}
.btn-chk:hover{transform:translateY(-1px);box-shadow:0 4px 14px rgba(37,99,235,.35);}
.empty-state{text-align:center;padding:50px 20px;}
.empty-state .ei{font-size:50px;margin-bottom:12px;}
.empty-state p{color:var(--mu);font-size:14px;margin-bottom:16px;}
.empty-state a{display:inline-block;padding:10px 24px;background:linear-gradient(135deg,#1d4ed8,#2563eb);color:#fff;border-radius:10px;font-weight:700;font-size:13px;text-decoration:none;}
.toast-msg{position:fixed;bottom:24px;left:50%;transform:translateX(-50%);
  background:linear-gradient(135deg,#1d4ed8,#2563eb);color:#fff;
  padding:10px 22px;border-radius:30px;font-size:13px;font-weight:700;
  box-shadow:0 6px 20px rgba(37,99,235,.4);z-index:9999;
  opacity:0;transition:opacity .3s;pointer-events:none;}
@media(max-width:500px){.stats{grid-template-columns:repeat(2,1fr);}.acard-head{flex-direction:column;align-items:flex-start;}}
</style>

<div class="page-wrapper">
<div class="page-content">
<div class="lp">

  <!-- Stats -->
  <div class="stats">
    <div class="sc sc-all">
      <div class="sc-ico">📋</div>
      <div><div class="sc-num"><?php echo $counts['Total']; ?></div><div class="sc-lbl">Total</div></div>
    </div>
    <div class="sc sc-ok">
      <div class="sc-ico">✅</div>
      <div><div class="sc-num"><?php echo $counts['Success']; ?></div><div class="sc-lbl">Success</div></div>
    </div>
    <div class="sc sc-pend">
      <div class="sc-ico">⏳</div>
      <div><div class="sc-num"><?php echo $counts['Pending']; ?></div><div class="sc-lbl">Pending</div></div>
    </div>
    <div class="sc sc-rej">
      <div class="sc-ico">❌</div>
      <div><div class="sc-num"><?php echo $counts['Rejected']; ?></div><div class="sc-lbl">Rejected</div></div>
    </div>
  </div>

  <!-- Main Card -->
  <div class="acard">
    <div class="acard-head">
      <div>
        <h5>🪪 <?php echo $page_title; ?></h5>
        <p><?php echo $is_admin ? 'Sare users ke PAN Find requests' : 'Aapke sare PAN Find requests'; ?></p>
      </div>
      <?php if(!$is_admin): ?>
      <a href="Pan_find1.php" class="new-btn">+ New Request</a>
      <?php endif; ?>
    </div>

    <div class="tscroll">
    <?php if(mysqli_num_rows($res) == 0): ?>
      <div class="empty-state">
        <div class="ei">🔍</div>
        <p>Koi request nahi mili.</p>
        <?php if(!$is_admin): ?><a href="Pan_find1.php">+ New Request Karo</a><?php endif; ?>
      </div>
    <?php else: ?>
    <table>
      <thead>
        <tr>
          <th>#</th>
          <?php if($is_admin): ?><th>User</th><?php endif; ?>
          <th>Aadhar</th>
          <th>PAN Result</th>
          <th>Status</th>
          <th>Date</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
      <?php $sno=1; mysqli_data_seek($res,0); while($row = mysqli_fetch_assoc($res)): $st=$row['status']; ?>
        <tr>
          <td style="color:var(--mu);font-size:12px;"><?php echo $sno++; ?></td>
          <?php if($is_admin): ?>
          <td><span class="uid-chip"><?php echo htmlspecialchars($row['username']); ?></span></td>
          <?php endif; ?>
          <td><span class="aadhar-chip">🪪 <?php echo htmlspecialchars($row['aadhar_no']); ?></span></td>
          <td id="pan-<?php echo $row['order_id']; ?>">
            <?php if($st=='Success' && !empty($row['pan_card_no']) && $row['pan_card_no'] != 'REJECTED'): ?>
              <span class="pan-result">
                <?php echo htmlspecialchars($row['pan_card_no']); ?>
                <button class="copy-btn" onclick="copyPan('<?php echo htmlspecialchars($row['pan_card_no']); ?>')" title="Copy">📋</button>
              </span>
            <?php elseif($st=='Rejected'): ?>
              <div style="font-size:11.5px;color:#dc2626;">⚠️ <?php echo htmlspecialchars($row['admin_remark'] ?? 'Rejected'); ?></div>
            <?php else: ?>
              <span style="color:var(--mu);font-size:12px;">Processing...</span>
            <?php endif; ?>
          </td>
          <td>
            <?php if($st=='Success'): ?>
              <span class="badge b-ok">✅ Success</span>
            <?php elseif($st=='Pending'): ?>
              <span class="badge b-pend">⏳ Pending</span>
            <?php else: ?>
              <span class="badge b-rej">❌ Rejected</span>
            <?php endif; ?>
          </td>
          <td style="font-size:11px;color:var(--mu);white-space:nowrap;">
            <?php echo date('d M Y', strtotime($row['date_time'])); ?><br>
            <?php echo date('h:i A', strtotime($row['date_time'])); ?>
          </td>
          <td>
            <?php if($st == 'Pending'): ?>
              <button class="btn-chk check-btn" data-id="<?php echo $row['order_id']; ?>">🔄 Check</button>
            <?php else: ?>
              <span style="font-size:11px;color:var(--mu);">✔ Done</span>
            <?php endif; ?>
          </td>
        </tr>
      <?php endwhile; ?>
      </tbody>
    </table>
    <?php endif; ?>
    </div>
  </div>

</div>
</div>
</div>

<div class="toast-msg" id="toast">📋 PAN Copied!</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$('.check-btn').on('click', function() {
    let orderid = $(this).data('id');
    Swal.fire({ title: 'Checking...', allowOutsideClick: false, didOpen: () => { Swal.showLoading(); } });
    $.get(window.location.href, { action: 'update', orderid: orderid }, function(res) {
        if(res.status == 'success') {
            Swal.fire('✅ PAN Found!', 'PAN: <b>' + res.pan + '</b>', 'success').then(()=> location.reload());
        } else if(res.status == 'error') {
            Swal.fire('❌ Rejected', res.msg, 'error').then(()=> location.reload());
        } else { 
            Swal.fire('⏳ Pending', res.msg, 'info'); 
        }
    });
});

function copyPan(pan){
  navigator.clipboard.writeText(pan).then(function(){
    var t=document.getElementById('toast');
    t.style.opacity='1';
    setTimeout(function(){t.style.opacity='0';},2200);
  }).catch(function(){
    var ta=document.createElement('textarea');
    ta.value=pan;ta.style.position='fixed';ta.style.opacity='0';
    document.body.appendChild(ta);ta.select();
    document.execCommand('copy');document.body.removeChild(ta);
    var t=document.getElementById('toast');
    t.style.opacity='1';
    setTimeout(function(){t.style.opacity='0';},2200);
  });
}
</script>

<?php include('../template/tngweb/footer.php'); ?>