<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/middleware.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/settings.php';
require_customer();

$uid = $_SESSION['user']['id'];
$id = (int)($_GET['id'] ?? 0);
$app = $pdo->prepare('SELECT a.*, s.service_name FROM applications a JOIN services s ON a.service_id=s.id WHERE a.id=? AND a.user_id=?'); $app->execute([$id,$uid]); $app = $app->fetch();
if (!$app) { include __DIR__ . '/../includes/header.php'; echo '<div class="card">Not found</div>'; include __DIR__ . '/../includes/footer.php'; exit; }

$det = $pdo->prepare('SELECT * FROM application_details WHERE application_id=?'); $det->execute([$id]); $det = $det->fetch();
$pay = $pdo->prepare('SELECT * FROM payments WHERE application_id=? ORDER BY id DESC LIMIT 1'); $pay->execute([$id]); $pay = $pay->fetch();
$cert = $pdo->prepare('SELECT * FROM certificates WHERE application_id=?'); $cert->execute([$id]); $cert = $cert->fetch();

include __DIR__ . '/../includes/header.php';
?>
<style>
/* Status Stepper */
.stepper {
    display: flex;
    justify-content: space-between;
    margin-bottom: 32px;
    position: relative;
}
.stepper::before {
    content: '';
    position: absolute;
    top: 14px;
    left: 0;
    right: 0;
    height: 2px;
    background: #e2e8f0;
    z-index: 0;
}
.step {
    position: relative;
    z-index: 1;
    background: #fff;
    padding: 0 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    flex: 1;
}
.step-circle {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background: #fff;
    border: 2px solid #e2e8f0;
    color: #94a3b8;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    transition: all 0.3s;
}
.step.active .step-circle {
    border-color: var(--primary);
    background: var(--primary);
    color: #fff;
}
.step.completed .step-circle {
    border-color: var(--primary);
    background: var(--primary);
    color: #fff;
}
.step-label {
    font-size: 12px;
    font-weight: 500;
    color: #64748b;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}
.step.active .step-label { color: var(--text); font-weight: 700; }

/* Layout */
.app-grid {
    display: grid;
    grid-template-columns: 1fr 340px;
    gap: 24px;
}
@media (max-width: 900px) {
    .app-grid { grid-template-columns: 1fr; }
    .stepper { overflow-x: auto; }
}

/* Info Row */
.info-row {
    display: flex;
    justify-content: space-between;
    padding: 12px 0;
    border-bottom: 1px solid var(--border);
}
.info-row:last-child { border-bottom: none; }
.info-label { color: var(--muted); font-size: 14px; }
.info-value { font-weight: 500; text-align: right; }

/* Payment Box */
.payment-box {
    background: #f8fafc;
    border: 1px solid var(--border);
    border-radius: 12px;
    padding: 20px;
}
.bank-details {
    background: #fff;
    border: 1px dashed #cbd5e1;
    border-radius: 8px;
    padding: 16px;
    margin: 16px 0;
    text-align: center;
}
.bank-name { font-weight: 600; color: var(--muted); font-size: 13px; text-transform: uppercase; }
.account-num { font-family: monospace; font-size: 24px; letter-spacing: 2px; font-weight: 700; margin: 4px 0; color: var(--text); }
.account-name { font-size: 14px; color: var(--muted); }

.timer-box {
    text-align: center;
    margin: 20px 0;
}
.timer-display {
    font-size: 32px;
    font-weight: 700;
    font-variant-numeric: tabular-nums;
    color: var(--primary);
}
</style>

<div style="margin-bottom:24px; display:flex; justify-content:space-between; align-items:center;">
    <div>
        <h1 style="margin:0; font-size:24px">Application #<?=e((string)$app['id'])?></h1>
        <p class="muted" style="margin:4px 0 0">Service: <?=e($app['service_name'])?></p>
    </div>
    <div class="chip chip-<?=e($app['status'])?>" style="font-size:14px; padding:6px 12px">
        <?=ucfirst($app['status'])?>
    </div>
</div>

<!-- Progress Stepper -->
<?php
$steps = ['draft' => 1, 'submitted' => 2, 'processing' => 3, 'approved' => 4];
$currentStep = $steps[$app['status']] ?? 1;
// Adjust logic: if rejected, maybe show processing as fail? For now standard flow.
?>
<div class="stepper">
    <div class="step <?=$currentStep >= 1 ? 'completed' : ''?> <?=$currentStep == 1 ? 'active' : ''?>">
        <div class="step-circle"><?=ui_icon('new', 14)?></div>
        <div class="step-label">Draft</div>
    </div>
    <div class="step <?=$currentStep >= 2 ? 'completed' : ''?> <?=$currentStep == 2 ? 'active' : ''?>">
        <div class="step-circle"><?=ui_icon('check', 14)?></div>
        <div class="step-label">Submitted</div>
    </div>
    <div class="step <?=$currentStep >= 3 ? 'completed' : ''?> <?=$currentStep == 3 ? 'active' : ''?>">
        <div class="step-circle"><?=ui_icon('processing', 14)?></div>
        <div class="step-label">Processing</div>
    </div>
    <div class="step <?=$currentStep >= 4 ? 'completed' : ''?> <?=$currentStep == 4 ? 'active' : ''?>">
        <div class="step-circle"><?=ui_icon('check', 14)?></div>
        <div class="step-label">Approved</div>
    </div>
</div>

<div class="app-grid">
    <!-- Main Content -->
    <div class="main-content">
        <?php if (!empty($app['admin_notes'])): ?>
        <div class="alert" style="margin-bottom:24px; background:#fff3cd; border-color:#ffeeba; color:#856404">
            <strong>Admin Note:</strong> <?=e($app['admin_notes'])?>
        </div>
        <?php endif; ?>

        <div class="card" style="margin-bottom:24px">
            <h3 style="margin-top:0">Business Details</h3>
            <?php if ($det): ?>
                <div class="info-row">
                    <span class="info-label">Proposed Name 1</span>
                    <span class="info-value"><?=e($det['proposed_name_1'] ?? '-')?></span>
                </div>
                <div class="info-row">
                    <span class="info-label">Proposed Name 2</span>
                    <span class="info-value"><?=e($det['proposed_name_2'] ?? '-')?></span>
                </div>
                <div class="info-row">
                    <span class="info-label">Business Nature</span>
                    <span class="info-value"><?=e($det['nature_of_business'] ?? '-')?></span>
                </div>
                <div class="info-row">
                    <span class="info-label">Address</span>
                    <span class="info-value"><?=e($det['business_address'] ?? '-')?></span>
                </div>
            <?php else: ?>
                <p class="muted">No details provided yet.</p>
            <?php endif; ?>
        </div>

        <div class="card">
            <h3 style="margin-top:0">Personal Information</h3>
            <?php if ($det): ?>
                <div class="info-row">
                    <span class="info-label">Full Name</span>
                    <span class="info-value"><?=e($det['full_name'] ?? '-')?></span>
                </div>
                <div class="info-row">
                    <span class="info-label">Email</span>
                    <span class="info-value"><?=e($det['email'] ?? '-')?></span>
                </div>
                <div class="info-row">
                    <span class="info-label">Phone</span>
                    <span class="info-value"><?=e($det['phone'] ?? '-')?></span>
                </div>
                
                <div style="margin-top:20px; display:flex; gap:12px; flex-wrap:wrap">
                    <?php if (!empty($det['id_document_path'])): ?>
                        <a href="<?=e($det['id_document_path'])?>" target="_blank" class="btn" style="background:#f1f5f9; color:var(--text)">
                            <?=ui_icon('open', 16)?> View ID Document
                        </a>
                    <?php endif; ?>
                    <?php if (!empty($det['passport_path'])): ?>
                        <a href="<?=e($det['passport_path'])?>" target="_blank" class="btn" style="background:#f1f5f9; color:var(--text)">
                            <?=ui_icon('open', 16)?> View Passport
                        </a>
                    <?php endif; ?>
                </div>
            <?php else: ?>
                <p class="muted">No details provided yet.</p>
            <?php endif; ?>
        </div>
    </div>

    <!-- Sidebar -->
    <div class="sidebar-col">
        <!-- Payment Module -->
        <div class="card payment-box">
            <h3 style="margin-top:0">Payment Status</h3>
            
            <?php if ($pay && $pay['status'] === 'confirmed'): ?>
                <div style="text-align:center; padding:20px 0">
                    <div style="width:48px; height:48px; background:#dcfce7; color:#16a34a; border-radius:50%; display:flex; align-items:center; justify-content:center; margin:0 auto 12px">
                        <?=ui_icon('check', 24)?>
                    </div>
                    <div style="font-weight:700; font-size:16px; color:#166534">Payment Confirmed</div>
                    <div class="muted" style="font-size:13px; margin-top:4px">Ref: <?=e($pay['provider_ref'])?></div>
                </div>
            <?php elseif ($app['status'] !== 'approved'): ?>
                <!-- Payment Flow -->
                <div id="payment-module">
                     <p style="font-size:14px; margin-bottom:16px">To process your application, please transfer the total amount below.</p>
                     
                     <div class="bank-details">
                         <div class="bank-name"><?= e(get_setting($pdo, 'bank_name', 'Guaranty Trust Bank (GTB)')) ?></div>
                         <div class="account-num"><?= e(get_setting($pdo, 'bank_account_number', '0123456789')) ?></div>
                         <div class="account-name"><?= e(get_setting($pdo, 'bank_account_name', 'Go Legal Services Ltd')) ?></div>
                     </div>
                     
                     <div style="display:flex; justify-content:space-between; margin-bottom:16px; font-weight:600">
                         <span>Total Amount</span>
                         <span>₦<?=e(money((float)$app['total_price'] > 0 ? (float)$app['total_price'] : ((float)$app['cac_fee'] + (float)$app['service_fee'])))?></span>
                     </div>

                     <div id="payment-step-1">
                        <button class="btn primary" id="start-payment-btn" style="width:100%; justify-content:center">
                            Start Payment Process
                        </button>
                     </div>

                     <div id="payment-step-2" style="display:none">
                        <div class="timer-box">
                            <div class="muted" style="font-size:12px; text-transform:uppercase">Time Remaining</div>
                            <div class="timer-display" id="payment-timer">30:00</div>
                        </div>
                        
                        <div class="input-bar" style="margin-bottom:12px">
                            <label style="font-size:12px">Transaction Reference / Sender Name</label>
                            <input type="text" id="payment-ref-input" placeholder="e.g. TRF-123456789">
                        </div>

                        <div class="input-bar" style="margin-bottom:20px">
                            <label style="font-size:12px">Upload Payment Receipt (Optional but recommended)</label>
                            <input type="file" id="payment-receipt-input" accept="image/*,.pdf" style="font-size:12px">
                        </div>

                        <button class="btn primary" id="confirm-payment-btn" style="width:100%; justify-content:center">
                            I Have Made The Transfer
                        </button>
                        <div id="payment-msg" style="margin-top:12px; font-size:13px; text-align:center; color:#dc2626"></div>
                     </div>
                </div>
            <?php else: ?>
                <p class="muted">No payment required.</p>
            <?php endif; ?>
        </div>

        <!-- Certificate -->
        <?php if ($cert): ?>
        <div class="card" style="margin-top:24px; text-align:center; background:#f0f9ff; border-color:#bae6fd">
            <h3 style="margin-top:0; color:#0369a1">Certificate Ready!</h3>
            <p style="font-size:14px; color:#0c4a6e; margin-bottom:16px">Your registration is complete.</p>
            <a class="btn primary" href="<?=e($cert['certificate_path'])?>" target="_blank" style="width:100%; justify-content:center">
                <?=ui_icon('download',18)?> Download Certificate
            </a>
        </div>
        <?php elseif ($app['status'] === 'approved'): ?>
             <div class="card" style="margin-top:24px">
                 <h3 style="margin-top:0">Certificate</h3>
                 <p class="muted">Generating certificate...</p>
             </div>
        <?php endif; ?>
        
        <div class="card" style="margin-top:24px">
            <h3 style="margin-top:0">Need Help?</h3>
            <p class="muted" style="font-size:14px">Contact support if you have any issues with your application.</p>
            <button onclick="document.getElementById('chat-toggle').click()" class="btn" style="width:100%; justify-content:center; margin-top:8px">Contact Support</button>
        </div>
    </div>
</div>

<script>
(function(){
  var appId = <?= (int)$app['id'] ?>;
  var amount = <?= (float)$app['total_price'] > 0 ? (float)$app['total_price'] : ((float)$app['cac_fee'] + (float)$app['service_fee']) ?>;
  var csrf = '<?= e($_SESSION['csrf_token'] ?? '') ?>';
  var startBtn = document.getElementById('start-payment-btn');
  var step1 = document.getElementById('payment-step-1');
  var step2 = document.getElementById('payment-step-2');
  var timerEl = document.getElementById('payment-timer');
  var confirmBtn = document.getElementById('confirm-payment-btn');
  var refInput = document.getElementById('payment-ref-input');
  var msgEl = document.getElementById('payment-msg');
  var intentId = null;
  var expiresAt = null;
  var timerInterval = null;

  if (!startBtn) return;

  function updateTimer() {
    if (!expiresAt) return;
    var now = new Date().getTime();
    var diff = expiresAt - now;
    if (diff <= 0) {
      clearInterval(timerInterval);
      timerEl.textContent = "00:00";
      msgEl.textContent = "Payment session expired. Please refresh to restart.";
      confirmBtn.disabled = true;
      return;
    }
    var m = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
    var s = Math.floor((diff % (1000 * 60)) / 1000);
    timerEl.textContent = (m<10?"0"+m:m) + ":" + (s<10?"0"+s:s);
  }

  function startTimer(expiryIso) {
    expiresAt = new Date(expiryIso).getTime();
    step1.style.display = 'none';
    step2.style.display = 'block';
    updateTimer();
    timerInterval = setInterval(updateTimer, 1000);
  }
  
  startBtn.addEventListener('click', function() {
    startBtn.disabled = true;
    startBtn.textContent = 'Starting...';
    
    var fd = new FormData();
    fd.append('action', 'create_intent');
    fd.append('csrf_token', csrf);
    fd.append('application_id', appId);
    fd.append('amount', amount);
    
    fetch('<?=url('api/payments.php')?>', {method:'POST', body:fd, credentials:'same-origin'})
      .then(r=>r.json())
      .then(function(res){
        if (res.error) {
          alert('Error: ' + res.error);
          startBtn.disabled = false;
          startBtn.textContent = 'Start Payment Process';
          return;
        }
        intentId = res.id;
        startTimer(res.expires_at);
      })
      .catch(function(){
        alert('Network error. Please try again.');
        startBtn.disabled = false;
        startBtn.textContent = 'Start Payment Process';
      });
  });

  confirmBtn.addEventListener('click', function() {
    var ref = refInput.value.trim();
    var receiptFile = document.getElementById('payment-receipt-input').files[0];
    
    if (ref.length < 3) {
      msgEl.textContent = "Please enter a valid reference or sender name.";
      return;
    }
    
    confirmBtn.disabled = true;
    confirmBtn.textContent = "Verifying...";
    msgEl.textContent = "";
    msgEl.style.color = 'var(--primary)';

    var fd = new FormData();
    fd.append('action', 'confirm');
    fd.append('csrf_token', csrf);
    fd.append('intent_id', intentId);
    fd.append('reference', ref);
    if (receiptFile) {
        fd.append('receipt', receiptFile);
    }


    fetch('/api/payments.php', {method:'POST', body:fd, credentials:'same-origin'})
      .then(r=>r.json())
      .then(function(res){
        if (res.error) {
          msgEl.textContent = "Error: " + res.error;
          confirmBtn.disabled = false;
          confirmBtn.textContent = "I Have Made The Transfer";
          return;
        }
        if (res.status === 'succeeded' || res.status === 'processing') {
          msgEl.style.color = 'green';
          msgEl.textContent = "Payment submitted successfully!";
          setTimeout(function(){ location.reload(); }, 1500);
        } else {
          msgEl.textContent = "Payment status: " + res.status;
          confirmBtn.disabled = false;
          confirmBtn.textContent = "I Have Made The Transfer";
        }
      })
      .catch(function(){
        msgEl.textContent = "Network error. Please check your connection.";
        confirmBtn.disabled = false;
        confirmBtn.textContent = "I Have Made The Transfer";
      });
  });

})();
</script>
<?php include __DIR__ . '/../includes/footer.php'; ?>
