<?php
require_once __DIR__ . '/../../app/helpers/functions.php';
require_once __DIR__ . '/../../app/helpers/csrf.php';
require_once __DIR__ . '/../../app/middleware/auth.php';

session_boot();
require_login();

$conn = require __DIR__ . '/../../app/config/database.php';
$u = current_user();

/* ===============================
   HANDLE KYC SUBMISSION
================================ */
if (is_post()) {
    csrf_verify();

    $type     = trim($_POST['kyc_type'] ?? '');
    $idNo     = trim($_POST['kyc_id_number'] ?? '');
    $country  = trim($_POST['kyc_country'] ?? '');

    if (!$type || !$idNo || !$country) {
        flash('msg','All fields are required.');
        redirect('kyc.php');
    }

    // upload helper
    function upload_kyc($file, $dir, $prefix, $uid) {
        if ($file['error'] !== 0) return null;

        $mime = mime_content_type($file['tmp_name']);
        if (!in_array($mime, ['image/jpeg','image/png'])) return null;

        $ext = $mime === 'image/png' ? 'png' : 'jpg';
        $name = "{$prefix}_{$uid}_" . time() . ".{$ext}";
        $path = "/uploads/kyc/{$dir}/{$name}";

        move_uploaded_file(
            $file['tmp_name'],
            __DIR__ . '/../../public' . $path
        );

        return $path;
    }

    $front  = upload_kyc($_FILES['front'] ?? [], 'front', 'front', $u['id']);
    $back   = upload_kyc($_FILES['back'] ?? [], 'back', 'back', $u['id']);
    $selfie = upload_kyc($_FILES['selfie'] ?? [], 'selfie', 'selfie', $u['id']);

    if (!$front || !$back) {
        flash('msg','Front and back of ID are required.');
        redirect('kyc.php');
    }

    $st = $conn->prepare("
        UPDATE users
        SET
          kyc_type=?,
          kyc_id_number=?,
          kyc_country=?,
          kyc_front=?,
          kyc_back=?,
          kyc_selfie=?,
          kyc_status='pending',
          kyc_submitted_at=NOW()
        WHERE id=?
    ");
    $st->bind_param(
        "ssssssi",
        $type,
        $idNo,
        $country,
        $front,
        $back,
        $selfie,
        $u['id']
    );
    $st->execute();

    flash('msg','KYC submitted successfully. Review in progress.');
    redirect('kyc.php');
}

$title = 'KYC Verification';
include __DIR__ . '/../../views/partials/head.php';
include __DIR__ . '/../../views/partials/customer_sidebar.php';
?>

<style>
.img-preview {
  width: 100%;
  max-height: 180px;
  object-fit: contain;
  border: 1px dashed #ddd;
  border-radius: 8px;
  background: #f8f9fa;
}
</style>
<main class="flex-grow-1" style="margin-left:240px; min-height:100vh;">
<div class="container-fluid py-4">

<?php if ($m = flash('msg')): ?>
  <div class="alert alert-info"><?= e($m) ?></div>
<?php endif; ?>

<div class="row g-4">

  <!-- LEFT: KYC FORM -->
  <div class="col-lg-7">
    <div class="card ab-card p-4 h-100">

      <h5 class="fw-bold mb-3">KYC Verification</h5>

      <div class="mb-3">
        Status:
        <span class="badge bg-<?= $u['kyc_status']==='verified'
          ? 'success'
          : (($u['kyc_status'] ?? '')==='rejected' ? 'danger' : 'warning') ?>">
          <?= e($u['kyc_status'] ?? 'not submitted') ?>
        </span>
      </div>

      <?php if (($u['kyc_status'] ?? '') !== 'verified'): ?>

      <form method="post" enctype="multipart/form-data">
        <?= csrf_field() ?>

        <label class="form-label">ID Type</label>
        <select name="kyc_type" class="form-select mb-2" required>
          <option value="">Select ID</option>
          <option value="national_id">National ID</option>
          <option value="passport">Passport</option>
          <option value="drivers_license">Driver’s License</option>
        </select>

        <label class="form-label">ID Number</label>
        <input name="kyc_id_number" class="form-control mb-2" required>

        <label class="form-label">Issuing Country</label>
        <input name="kyc_country" class="form-control mb-3" required>

        <div class="row g-2">
          <div class="col-md-6">
            <label class="form-label">ID Front</label>
            <input type="file" name="front" class="form-control" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">ID Back</label>
            <input type="file" name="back" class="form-control" required>
          </div>
        </div>

        <label class="form-label mt-3">
          Selfie with ID <span class="ab-muted">(optional)</span>
        </label>
        <input type="file" name="selfie" class="form-control mb-3">

        <button class="btn ab-btn text-white w-100">
          Submit KYC
        </button>
      </form>

      <?php else: ?>
        <div class="alert alert-success mt-3">
          Your identity has been verified.
        </div>
      <?php endif; ?>

    </div>
  </div>

  <!-- RIGHT: GUIDE / IMAGE -->
  <div class="col-lg-5">
    <div class="card ab-card p-4 h-100">

      <h6 class="fw-bold mb-3">How to submit your ID</h6>

<img
  src="../assets/kyc/kyc-sample.png"
  class="img-fluid rounded mb-3"
  alt="KYC sample"
>


      <ul class="ab-muted small ps-3">
        <li>Upload a clear photo of your ID</li>
        <li>All corners must be visible</li>
        <li>No blur or glare</li>
        <li>Name must match your profile</li>
        <li>Accepted formats: JPG, PNG</li>
      </ul>

      <div class="alert alert-warning small mt-3">
        ⚠ Submitting fake or altered documents may lead to account suspension.
      </div>

    </div>
  </div>

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

<script>
function previewImage(input, previewId) {
  const file = input.files[0];
  if (!file) return;

  const img = document.getElementById(previewId);
  img.src = URL.createObjectURL(file);
  img.classList.remove('d-none');
}
</script>


<?php include __DIR__ . '/../../views/partials/foot.php'; ?>
