<?php
session_start();
error_reporting(0);
include('config.php');
include "auth_guard.php";
/* -----------------------------
   1) Reliable image download proxy
   ----------------------------- */
if (isset($_GET['dl'])) {
  // allow only a safe basename like "file.jpg"
  $fname = basename($_GET['dl']);
  // basic allowlist (letters, numbers, dot, dash, underscore)
  if (!preg_match('/^[A-Za-z0-9._-]+$/', $fname)) {
    http_response_code(400);
    echo "Invalid filename.";
    exit;
  }

  $base = 'https://test.traderssolution.com/crmvideonew/_docs/';
  $url  = $base . rawurlencode($fname);

  // Try to stream the remote file (allow_url_fopen must be enabled)
  $ctx  = stream_context_create(['http' => ['timeout' => 15]]);
  $data = @file_get_contents($url, false, $ctx);
  if ($data === false) {
    http_response_code(404);
    echo "File not found or inaccessible.";
    exit;
  }

  // Guess content-type from extension
  $ext = strtolower(pathinfo($fname, PATHINFO_EXTENSION));
  $mime = 'application/octet-stream';
  if (in_array($ext, ['jpg','jpeg'])) $mime = 'image/jpeg';
  elseif ($ext === 'png') $mime = 'image/png';
  elseif ($ext === 'gif') $mime = 'image/gif';
  elseif ($ext === 'pdf') $mime = 'application/pdf';

  header('Content-Type: ' . $mime);
  header('Content-Length: ' . strlen($data));
  header('Content-Disposition: attachment; filename="' . $fname . '"');
  header('Cache-Control: no-store');
  echo $data;
  exit;
}

/* -----------------------------
   2) Handle admin action (Approve/Not Approve)
   ----------------------------- */
if (isset($_POST['update'])) {
  $did        = intval($_GET['id'] ?? 0);
  $email      = $_GET['email'] ?? '';
  $description= $_POST['description'] ?? '';
  $status     = $_POST['status'] ?? '';

  $sql = "UPDATE kyc_update SET Admin_Remark=:description, Status=:status WHERE id=:did";
  $query = $conn->prepare($sql);
  $query->bindParam(':description', $description, PDO::PARAM_STR);
  $query->bindParam(':status', $status, PDO::PARAM_INT);
  $query->bindParam(':did', $did, PDO::PARAM_INT);
  $query->execute();

  if ((int)$status === 1 && !empty($email)) {
    $sql = "UPDATE aspnetusers SET kyc_verify=:status WHERE email=:email";
    $query = $conn->prepare($sql);
    $query->bindParam(':status', $status, PDO::PARAM_INT);
    $query->bindParam(':email', $email, PDO::PARAM_STR);
    $query->execute();
  }

  echo "<script>alert('User KYC Updated Successfully');</script>";
}

/* -----------------------------
   3) Fetch single KYC record
   ----------------------------- */
$id = intval($_GET['id'] ?? 0);
$sql = "SELECT * FROM kyc_update WHERE id=:id";
$query = $conn->prepare($sql);
$query->bindParam(':id', $id, PDO::PARAM_INT);
$query->execute();
$row = $query->fetch(PDO::FETCH_OBJ);
?>
<head><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body class="bg-gray-100 is-app with-sidebar">
<?php include "header.php";?>

<style>
  :root{
    --sidebar-w: 260px;    /* set this to your actual sidebar width */
    --topbar-h: 64px;
    --max-wrap: 1200px;    /* cap main content width */
    --card:#fff; --ink:#0f172a; --muted:#64748b; --ring:rgba(2,132,199,.25);
    --ok:#16a34a; --warn:#f59e0b; --bad:#dc2626; --brand:#db6612; --brand-dark:#0284c7;
  }

  /* Assume your sidebar is fixed */
  .sidebar, .app-sidebar{ position:fixed; left:0; top:0; bottom:0; width:var(--sidebar-w); z-index:1000; }

  /* Push main next to sidebar */
  body.with-sidebar .dashboard-content-one{
    margin-left: var(--sidebar-w);
    padding: 24px;
    min-height: calc(100vh - var(--topbar-h));
  }

  /* Max width center */
  .wrap{ max-width: var(--max-wrap); margin-inline:auto; }

  /* Page head */
  .page-head{
    display:flex; align-items:center; justify-content:space-between; gap:12px;
    padding:16px 20px; background:var(--card);
    border:1px solid #e5e7eb; border-radius:14px;
    box-shadow:0 8px 24px rgba(2,6,23,.06);
    margin-bottom:18px;
  }
  .page-title{ font-weight:700; color:var(--ink); font-size:20px; }
  .btn{ display:inline-flex; align-items:center; border-radius:999px; padding:8px 14px; font-weight:600; border:0; cursor:pointer; }
  .btn-outline{ background:transparent; color:#db6612; border:1px solid #db6612; }
  .btn-outline:hover{ background:#db6612; color:#fff; }
  .btn-primary{ background:#db6612; color:#fff; }
  .btn-primary:hover{ background:orange; }
  .btn-success{ background:#16a34a; color:#fff; }
  .btn-secondary{ background:#475569; color:#fff; }
  .btn-sm{ padding:6px 12px; font-size:12px; }

  /* Grid */
  .grid{ display:grid; grid-template-columns: 1fr 1fr; gap:20px; }
  @media (max-width: 980px){ .grid{ grid-template-columns: 1fr; } }

  /* Cards */
  .card{ background:var(--card); border:1px solid #e5e7eb; border-radius:16px; box-shadow:0 12px 30px rgba(2,6,23,.06); }
  .card .card-head{ padding:12px 16px; border-bottom:1px solid #eef2f7; display:flex; align-items:center; justify-content:space-between; }
  .card .card-body{ padding:16px; }

  /* Details table */
  .kv{ width:100%; border-collapse:separate; border-spacing:0 8px; }
  .kv td{ padding:6px 8px; vertical-align:top; }
  .kv td:first-child{ width:180px; color:#334155; font-weight:600; }
  .muted{ color:var(--muted); }
  .amount{ font-weight:600; color:#0f172a; }

  /* Badges */
  .badge{ display:inline-block; padding:.35rem .6rem; font-size:12px; font-weight:700; border-radius:999px; }
  .badge-success{ background:rgba(22,163,74,.12); color:#15803d; }
  .badge-primary{ background:rgba(2,132,199,.12); color:#0369a1; }
  .badge-danger{  background:rgba(220,38,38,.12); color:#b91c1c; }

  /* Image block (fixed size) */
  .doc-block{ text-align:center; }
  .doc-img{
    width: 340px;       /* fixed width */
    height: 220px;      /* fixed height */
    object-fit: cover;  /* uniform look; use 'contain' if you prefer full image */
    border:1px solid #e5e7eb; border-radius:12px; background:#f8fafc;
    box-shadow: inset 0 0 0 1px #f1f5f9;
  }
  .doc-actions{ margin-top:10px; display:flex; justify-content:center; gap:10px; }

  /* Make images wrap nicely on smaller screens */
  @media (max-width: 520px){
    .doc-img{ width: 100%; height: 220px; }
  }
</style>

<div class="flex h-screen">
  <?php include "side_bar.php";?>

  <div class="dashboard-content-one">
    <div class="wrap">

      <!-- Page Head -->
      <div class="page-head">
        <div class="page-title">KYC Details</div>
        <div class="actions">
          <a href="kyc.php" class="btn btn-outline">Get Back</a>
          <button type="button" class="btn btn-primary" onclick="location.reload()">Refresh</button>
        </div>
      </div>

      <?php if ($row): ?>
      <div class="grid">
        <!-- LEFT: KYC Meta -->
        <div class="card">
          <div class="card-head">
            <h5 style="margin:0;">1. KYC Details</h5>
            <?php if ((int)$row->Status === 0): ?>
              <!-- Bootstrap 4 attributes -->
<div class="card-head">

  <?php if ((int)$row->Status === 0): ?>
    <button type="button"
            class="btn btn-success"
            data-toggle="modal"
            data-target="#kycActionModal" style="background-color:orange;">
      Take&nbsp;Action
    </button>
  <?php endif; ?>
</div>

            <?php endif; ?>
          </div>
          <div class="card-body">
            <table class="kv">
              <tbody>
                <tr>
                  <td>KYC ID</td>
                  <td>:&nbsp; <?= htmlentities($row->id) ?></td>
                </tr>
                <tr>
                  <td>Client Email</td>
                  <td>:&nbsp; <?= htmlentities($row->email) ?></td>
                </tr>
                <tr>
                  <td>KYC Type</td>
                  <td>:&nbsp; <span class="amount"><?= htmlentities($row->kyc_type) ?></span></td>
                </tr>
                <tr>
                  <td>KYC Request Date</td>
                  <td>:&nbsp; <?= htmlentities($row->registered_date_js) ?></td>
                </tr>
                <tr>
                  <td>KYC Status</td>
                  <td>
                    :&nbsp;
                    <?php
                      $stats = (int)$row->Status;
                      if ($stats === 1)  echo '<span class="badge badge-success">Approved</span>';
                      elseif ($stats === 2) echo '<span class="badge badge-primary">Not Approved</span>';
                      else                  echo '<span class="badge badge-danger">Waiting for approval</span>';
                    ?>
                  </td>
                </tr>
                <tr>
                  <td>Admin Remark</td>
                  <td>
                    :&nbsp;
                    <?php
                      echo $row->Admin_Remark === '' ? '<span class="muted">Waiting for approval</span>' : htmlentities($row->Admin_Remark);
                    ?>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <!-- RIGHT: Documents -->
        <div class="card">
          <div class="card-body">
            <!-- Front -->
            <div class="card" style="margin-bottom:16px;">
              <div class="card-head">
                <h5 style="margin:0;"><?= htmlentities($row->kyc_type) ?> <?= htmlentities($row->kyc_frontside) ?></h5>
              </div>
              <div class="card-body doc-block">
                <img class="doc-img"
                     src="https://test.traderssolution.com/crmvideonew/_docs/<?= htmlentities($row->front_image) ?>"
                     alt="Front document">
                <div class="doc-actions">
                  <!-- Force download via same-page proxy -->
                  <a class="btn btn-outline btn-sm"
                     href="?id=<?= urlencode($row->id) ?>&email=<?= urlencode($row->email) ?>&dl=<?= urlencode(basename($row->front_image)) ?>">
                    Download
                  </a>
                </div>
              </div>
            </div>

            <!-- Back -->
            <div class="card">
              <div class="card-head">
                <h5 style="margin:0;"><?= htmlentities($row->kyc_type) ?> <?= htmlentities($row->kyc_backside) ?></h5>
              </div>
              <div class="card-body doc-block">
                <img class="doc-img"
                     src="https://test.traderssolution.com/crmvideonew/_docs/<?= htmlentities($row->back_image) ?>"
                     alt="Back document">
                <div class="doc-actions">
                  <!-- Force download via same-page proxy -->
                  <a class="btn btn-outline btn-sm"
                     href="?id=<?= urlencode($row->id) ?>&email=<?= urlencode($row->email) ?>&dl=<?= urlencode(basename($row->back_image)) ?>">
                    Download
                  </a>
                </div>
              </div>
            </div>

          </div>
        </div>
      </div><!-- /.grid -->

      <?php else: ?>
        <div class="card">
          <div class="card-body" style="padding:20px; color:#475569;">
            Record not found.
          </div>
        </div>
      <?php endif; ?>

    </div><!-- /.wrap -->
  </div><!-- /.dashboard-content-one -->
</div><!-- /.flex -->
<?php if ($row && (int)$row->Status === 0): ?>
  <form method="post" id="adminactionForm">
    <div class="modal fade" id="kycActionModal" tabindex="-1" role="dialog" aria-labelledby="kycActionLabel" aria-hidden="true" style="margin-top:30px;">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="kycActionLabel" >KYC Take Action</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>

          <div class="modal-body">
            <div class="form-group">
              <label class="form-control-label text-danger">Action</label>
              <select name="status" class="form-control" required>
                <option value="">Choose your option</option>
                <option value="1">Approved</option>
                <option value="2">Not Approved</option>
              </select>
            </div>

            <div class="form-group">
              <label class="form-control-label text-danger">Description</label>
              <textarea class="form-control" name="description" rows="4" required></textarea>
            </div>
          </div>

          <div class="modal-footer">
            <button type="submit" name="update" class="btn btn-primary">Update</button>
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          </div>
        </div>
      </div>
    </div>
  </form>
<?php endif; ?>




<!-- If your footer already includes these, you can remove the duplicates -->
<!-- Bootstrap 4 dependencies to ensure the modal works -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
