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

/* ===== DATE FILTER (DEFAULT TODAY) ===== */
$from = $_GET['from'] ?? date('Y-m-d');
$to   = $_GET['to']   ?? date('Y-m-d');

$fromSql = mysqli_real_escape_string($tng_conn,$from.' 00:00:00');
$toSql   = mysqli_real_escape_string($tng_conn,$to.' 23:59:59');
?>

<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">

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

<div class="card luxury-card">
<div class="card-body">

<div class="d-flex justify-content-between align-items-center mb-3">
  <a href="javascript:history.back()" class="btn btn-outline-primary rounded-pill px-4">
    <i class="bi bi-arrow-left-circle me-2"></i> Go Back
  </a>
  <h5 class="fw-bold text-primary mb-0">📂 All PDF / Service History</h5>
</div>

<hr>

<!-- ===== DATE FILTER UI (NEW – baki sab same) ===== -->
<form method="get" class="row g-3 align-items-end mb-3">
  <div class="col-md-3">
    <label class="fw-semibold">From Date</label>
    <input type="date" name="from" value="<?= htmlspecialchars($from) ?>" class="form-control rounded-pill">
  </div>

  <div class="col-md-3">
    <label class="fw-semibold">To Date</label>
    <input type="date" name="to" value="<?= htmlspecialchars($to) ?>" class="form-control rounded-pill">
  </div>

  <div class="col-md-4">
    <button class="btn btn-primary rounded-pill px-4 me-2">
      🔍 Filter
    </button>
    <a href="all_history.php" class="btn btn-outline-secondary rounded-pill px-4">
      ♻ Today
    </a>
  </div>
</form>

<div class="table-responsive">
<table id="walletTable" class="table table-hover luxury-table align-middle text-center">
<thead>
<tr>
  <th>Sr No</th>
  <th>Service</th>
  <th>Name</th>
  <th>Number</th>
  <th>Date</th>
  <th>Action</th>
</tr>
</thead>
<tbody>

<?php
/* ===== DATA FETCH (sirf condition add hui) ===== */
if ($udata['type'] === 'admin') {
    $res = mysqli_query(
        $tng_conn,
        "SELECT * FROM all_pdf_records
         WHERE date BETWEEN '$fromSql' AND '$toSql'
         ORDER BY date DESC"
    );
} else {
    $phone = mysqli_real_escape_string($tng_conn,$udata['phone']);
    $res = mysqli_query(
        $tng_conn,
        "SELECT * FROM all_pdf_records
         WHERE username='$phone'
         AND date BETWEEN '$fromSql' AND '$toSql'
         ORDER BY date DESC"
    );
}

while($row = mysqli_fetch_assoc($res)){

$raw = trim($row['pdf']);

/* ===== FILE NAME SAFE ===== */
$nameRaw = $row['service_name'].'_'.$row['name'].'_'.$row['number'];
$nameRaw = preg_replace('/\s+/', '_', $nameRaw);
$nameRaw = preg_replace('/[^a-zA-Z0-9_]/', '_', $nameRaw);
$nameRaw = preg_replace('/_+/', '_', $nameRaw);
$fileName = strtoupper(trim($nameRaw,'_'));

/* ===== TYPE DETECT ===== */
$isPdf   = strpos($raw,'data:application/pdf;base64,') === 0;
$isImage = preg_match('#^data:image/(png|jpeg|jpg);base64,#', $raw);
?>

<tr>
<td></td>

<td>
<span class="badge bg-info text-dark px-3 py-2">
<?= strtoupper(str_replace('_',' ',$row['service_name'])) ?>
</span>
</td>

<td><?= htmlspecialchars($row['name']) ?></td>
<td><?= htmlspecialchars($row['number']) ?></td>

<td data-order="<?= strtotime($row['date']) ?>">
<?= date("d M Y h:i A",strtotime($row['date'])) ?>
</td>

<td>
<?php if($isPdf){ ?>
<button class="btn btn-success btn-sm rounded-pill px-4"
onclick="downloadPdfBase64('<?= htmlspecialchars($raw,ENT_QUOTES) ?>','<?= $fileName ?>')">
⬇️ Download PDF
</button>

<?php } elseif($isImage){ ?>
<button class="btn btn-warning btn-sm rounded-pill px-4"
onclick="downloadImageBase64('<?= htmlspecialchars($raw,ENT_QUOTES) ?>','<?= $fileName ?>')">
🖼️ Download Image
</button>

<?php } elseif(!empty($raw)){ ?>
<button class="btn btn-primary btn-sm rounded-pill px-4"
onclick='openUniversalViewer(<?= htmlspecialchars(json_encode(
    base64_decode(preg_replace("#^data:\w+/\w+;base64,#","",$raw))
),ENT_QUOTES) ?>)'>
👁️ View Details
</button>
<?php } else { ?>
<span class="text-muted">N/A</span>
<?php } ?>
</td>
</tr>

<?php } ?>

</tbody>
</table>
</div>

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

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

<!-- ================= JS ================= -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
$(function(){
  const table = $('#walletTable').DataTable({
    pageLength:10,
    lengthChange:false,
    order:[[4,'desc']],
    columnDefs:[{orderable:false,targets:[0,5]}]
  });

  table.on('order.dt search.dt',function(){
    table.column(0,{search:'applied',order:'applied'})
         .nodes().each((cell,i)=>cell.innerHTML=i+1);
  }).draw();
});
</script>

<!-- ================= PDF DOWNLOAD (ALL DEVICES) ================= -->
<script>
function downloadPdfBase64(dataUrl,filename){
  try{
    const base64 = dataUrl.replace(/^data:application\/pdf;base64,/, '');
    const binary = atob(base64);
    const bytes  = new Uint8Array(binary.length);
    for(let i=0;i<binary.length;i++) bytes[i]=binary.charCodeAt(i);

    const blob = new Blob([bytes],{type:'application/pdf'});
    const url  = URL.createObjectURL(blob);

    const a = document.createElement('a');
    a.href = url;
    a.download = filename+'.pdf';
    a.target = '_self';
    document.body.appendChild(a);

    setTimeout(()=>a.click(),50);
    setTimeout(()=>{
      URL.revokeObjectURL(url);
      document.body.removeChild(a);
    },3000);
  }catch(e){
    Swal.fire('Error','PDF download failed','error');
  }
}
</script>

<!-- ================= IMAGE DOWNLOAD ================= -->
<script>
function downloadImageBase64(dataUrl,filename){
  try{
    const arr = dataUrl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    const u8   = new Uint8Array(bstr.length);
    for(let i=0;i<bstr.length;i++) u8[i]=bstr.charCodeAt(i);

    const blob = new Blob([u8],{type:mime});
    const url  = URL.createObjectURL(blob);

    const a = document.createElement('a');
    a.href = url;
    a.download = filename+'.png';
    a.target='_self';
    document.body.appendChild(a);
    setTimeout(()=>a.click(),50);

    setTimeout(()=>{
      URL.revokeObjectURL(url);
      document.body.removeChild(a);
    },3000);
  }catch(e){
    Swal.fire('Error','Image download failed','error');
  }
}
</script>

<!-- ================= JSON VIEW (SWAL) ================= -->
<script>
function openUniversalViewer(raw){
  let data;
  try{ data = JSON.parse(raw); }catch(e){ data = raw; }

  const root = document.createElement('div');
  root.className='json-root';
  renderJson(data,root);

  Swal.fire({
    title:'📄 Service Details',
    html:root,
    width:'90%',
    showCancelButton:true,
    confirmButtonText:'📋 Copy Details',
    cancelButtonText:'❌ Close',
    customClass:{popup:'swal-lux'},
    didOpen:()=> window.__COPY = root.innerText.trim(),
    preConfirm:()=>{
      navigator.clipboard.writeText(window.__COPY);
      Swal.fire('Copied','Visible details copied','success');
      return false;
    }
  });
}

function renderJson(d,c){
  if(d===null||typeof d!=='object'){ c.appendChild(val(d));return; }
  if(Array.isArray(d)){
    d.forEach((i,x)=>{
      const box=document.createElement('div');
      box.className='json-card';
      box.innerHTML=`<div class="json-card-title">Item ${x+1}</div>`;
      renderJson(i,box); c.appendChild(box);
    }); return;
  }
  const t=document.createElement('table');
  t.className='table table-bordered json-table';
  for(const k in d){
    const tr=document.createElement('tr');
    const th=document.createElement('th');
    const td=document.createElement('td');
    th.innerText=beautify(k);
    renderJson(d[k],td);
    tr.appendChild(th); tr.appendChild(td);
    t.appendChild(tr);
  }
  c.appendChild(t);
}

function beautify(k){
  const map={
    fullname:'Full Name',
    fathername:'Father Name',
    mobileNumber:'Mobile Number',
    data_count:'Data Count',
    sr_no:'Sr No'
  };
  if(map[k]) return map[k];
  return k.replace(/_/g,' ')
          .replace(/([A-Z])/g,' $1')
          .replace(/^./,c=>c.toUpperCase());
}

function val(v){
  const s=document.createElement('span');
  s.className='json-value';
  s.innerText=(v===null||v==='')?'-':v;
  return s;
}
</script>

<style>
body{background:#f4f6fb}
.luxury-card{
  border-radius:20px;
  background:linear-gradient(145deg,#fff,#eef2ff);
  box-shadow:0 20px 40px rgba(0,0,0,.08);
}
.luxury-table thead th{ 
  background:linear-gradient(135deg,#1e1e2f,#2f3350);
  color:#fff;
}
.luxury-table tbody tr:hover{background:#eef2ff}
.swal-lux{border-radius:20px!important}
.json-root{max-height:70vh;overflow:auto}
.json-table th{width:30%;background:#eef2ff;font-weight:600}
.json-card{
  background:#fff;border-radius:16px;
  padding:14px;margin-bottom:14px;
  box-shadow:0 10px 25px rgba(0,0,0,.06)
}
.json-card-title{font-weight:700;color:#4338ca;margin-bottom:8px}
.json-value{
  background:#f8fafc;
  padding:6px 10px;
  border-radius:8px;
  display:inline-block
}
</style>
