<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';
require_once 'includes/auth.php';
requireUserLogin();
$currentUser = currentUser($pdo);
$uid = (int)$_SESSION['user_id'];

$error = ''; $success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && verify_csrf()) {
    $docType   = $_POST['document_type'] ?? '';
    $docNumber = trim($_POST['document_number'] ?? '');
    $expiry    = $_POST['expiry_date'] ?? '';
    $country   = trim($_POST['country_issued'] ?? '');

    if (!$docType || empty($_FILES['document']['name'])) {
        $error = 'Please select a document type and upload your document.';
    } else {
        $docPath = uploadFile($_FILES['document'], KYC_PATH, ['image/jpeg','image/png','application/pdf']);
        if (!$docPath) { $error = 'Document upload failed. Use JPG/PNG/PDF under 5MB.'; goto done; }

        $backPath = null;
        if (!empty($_FILES['back_doc']['name'])) {
            $backPath = uploadFile($_FILES['back_doc'], KYC_PATH) ?: null;
        }
        $selfiePath = null;
        if (!empty($_FILES['selfie']['name'])) {
            $selfiePath = uploadFile($_FILES['selfie'], KYC_PATH) ?: null;
        }

        // Mark old pending as rejected
        $pdo->prepare("UPDATE kyc_documents SET status='rejected',rejection_reason='Superseded by new submission' WHERE user_id=? AND status='pending'")->execute([$uid]);
        $pdo->prepare("INSERT INTO kyc_documents (user_id,document_type,document_number,document_path,back_path,selfie_path,expiry_date,country_issued,status) VALUES (?,?,?,?,?,?,?,?,'pending')")->execute([$uid,$docType,$docNumber,$docPath,$backPath,$selfiePath,$expiry,$country]);
        $pdo->prepare("UPDATE users SET kyc_status='pending' WHERE id=?")->execute([$uid]);
        addNotification($pdo, $uid, 'KYC Submitted', 'Your KYC documents have been submitted and are under review. We will notify you once verified.', 'info');
        logActivity($pdo, $uid, null, 'kyc_submit', 'User submitted KYC: ' . $docType);
        $success = 'KYC documents submitted successfully! We will review them within 24-48 hours.';
        $currentUser = getUserById($pdo, $uid);
    }
}
done:

$kycDocs = $pdo->prepare("SELECT * FROM kyc_documents WHERE user_id=? ORDER BY created_at DESC");
$kycDocs->execute([$uid]); $docs = $kycDocs->fetchAll();
$latestDoc = $docs[0] ?? null;

$pageTitle = 'KYC Verification';
?>
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= $pageTitle ?> | <?= SITE_NAME ?></title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link rel="stylesheet" href="/assets/css/style.css">
</head><body>
<?php include 'includes/header.php'; ?>
<div class="page-wrapper"><div class="container" style="max-width:760px;">
<div class="page-title"><i class="fa fa-id-card me-2 text-danger"></i>KYC Verification</div>

<?php if ($error): ?><div class="alert alert-danger"><?= sanitize($error) ?></div><?php endif; ?>
<?php if ($success): ?><div class="alert alert-success"><?= sanitize($success) ?></div><?php endif; ?>

<!-- Status Banner -->
<div class="card mb-4 <?= ['pending'=>'border-warning','verified'=>'border-success','rejected'=>'border-danger','under_review'=>'border-info'][$currentUser['kyc_status']] ?? 'border-secondary' ?>">
  <div class="card-body d-flex align-items-center gap-3">
    <?php $icons=['pending'=>'⏳','verified'=>'✅','rejected'=>'❌','under_review'=>'🔍'];
    echo '<span style="font-size:2rem;">' . ($icons[$currentUser['kyc_status']]??'❓') . '</span>'; ?>
    <div>
      <h5 class="mb-1">KYC Status: <?= statusBadge($currentUser['kyc_status']) ?></h5>
      <?php if ($currentUser['kyc_status']==='verified'): ?>
        <p class="mb-0 text-success">Your identity has been verified. You have full access.</p>
      <?php elseif ($currentUser['kyc_status']==='pending'): ?>
        <p class="mb-0 text-warning">Your documents are under review. This usually takes 24-48 hours.</p>
      <?php elseif ($currentUser['kyc_status']==='rejected'): ?>
        <p class="mb-0 text-danger">Your verification was rejected. <?= $latestDoc?sanitize($latestDoc['rejection_reason']??''):'' ?> Please resubmit.</p>
      <?php else: ?>
        <p class="mb-0 text-muted">Complete KYC to unlock transfers and full account access.</p>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- Steps -->
<div class="card mb-4">
  <div class="card-header">Verification Steps</div>
  <div class="card-body">
    <div class="kyc-step <?= $currentUser['kyc_status']==='verified'?'done':'' ?>">
      <div class="step-num">1</div>
      <div><strong>Create Account</strong><p class="mb-0 text-muted small">Your account is active.</p></div>
    </div>
    <div class="kyc-step <?= in_array($currentUser['kyc_status'],['pending','under_review','verified'])?'done':'' ?>">
      <div class="step-num">2</div>
      <div><strong>Submit Documents</strong><p class="mb-0 text-muted small">Upload government-issued ID.</p></div>
    </div>
    <div class="kyc-step <?= $currentUser['kyc_status']==='verified'?'done':'' ?>">
      <div class="step-num">3</div>
      <div><strong>Verification</strong><p class="mb-0 text-muted small">Our team reviews your documents within 24-48h.</p></div>
    </div>
    <div class="kyc-step <?= $currentUser['kyc_status']==='verified'?'done':'' ?>">
      <div class="step-num">4</div>
      <div><strong>Full Access Unlocked</strong><p class="mb-0 text-muted small">Make transfers, manage cards, and more.</p></div>
    </div>
  </div>
</div>

<?php if ($currentUser['kyc_status'] !== 'verified'): ?>
<!-- Upload Form -->
<div class="card mb-4">
  <div class="card-header">Submit Documents</div>
  <div class="card-body">
    <form method="POST" enctype="multipart/form-data">
      <?= csrf_field() ?>
      <div class="row g-3">
        <div class="col-md-6">
          <label class="form-label">Document Type *</label>
          <select name="document_type" class="form-select" required>
            <option value="">Select type</option>
            <option value="national_id">National ID</option>
            <option value="passport">International Passport</option>
            <option value="drivers_license">Driver's License</option>
            <option value="utility_bill">Utility Bill</option>
            <option value="bank_statement">Bank Statement</option>
            <option value="tax_id">Tax ID</option>
          </select>
        </div>
        <div class="col-md-6">
          <label class="form-label">Document Number</label>
          <input type="text" name="document_number" class="form-control" placeholder="ID/passport number">
        </div>
        <div class="col-md-6">
          <label class="form-label">Expiry Date</label>
          <input type="date" name="expiry_date" class="form-control">
        </div>
        <div class="col-md-6">
          <label class="form-label">Country Issued</label>
          <input type="text" name="country_issued" class="form-control" placeholder="e.g. United States">
        </div>
        <div class="col-12">
          <label class="form-label">Front of Document * <small class="text-muted">(JPG/PNG/PDF, max 5MB)</small></label>
          <input type="file" name="document" class="form-control" accept="image/*,application/pdf" required>
        </div>
        <div class="col-12">
          <label class="form-label">Back of Document <small class="text-muted">(optional)</small></label>
          <input type="file" name="back_doc" class="form-control" accept="image/*,application/pdf">
        </div>
        <div class="col-12">
          <label class="form-label">Selfie with Document <small class="text-muted">(optional but recommended)</small></label>
          <input type="file" name="selfie" class="form-control" accept="image/*">
        </div>
      </div>
      <button class="btn btn-primary mt-3 px-4"><i class="fa fa-upload me-2"></i>Submit for Verification</button>
    </form>
  </div>
</div>
<?php endif; ?>

<!-- History -->
<?php if (!empty($docs)): ?>
<div class="card">
  <div class="card-header">Submission History</div>
  <div class="table-responsive">
    <table class="table mb-0 small">
      <thead><tr><th>Date</th><th>Type</th><th>Number</th><th>Country</th><th>Status</th><th>Remarks</th></tr></thead>
      <tbody>
      <?php foreach ($docs as $d): ?>
      <tr>
        <td><?= formatDate($d['created_at'],'M j, Y') ?></td>
        <td><?= ucfirst(str_replace('_',' ',$d['document_type'])) ?></td>
        <td><?= sanitize($d['document_number']??'—') ?></td>
        <td><?= sanitize($d['country_issued']??'—') ?></td>
        <td><?= statusBadge($d['status']) ?></td>
        <td class="text-danger small"><?= sanitize($d['rejection_reason']??'') ?></td>
      </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>
<?php endif; ?>

</div></div>
<?php include 'includes/footer.php'; ?>
</body></html>
