<?php
require_once "includes/config.php";
require_once "includes/functions.php";

if (!is_logged_in()) {
  header("Location: /myukstore/auth/login.php?redirect=/myukstore/checkout.php");
  exit;
}

$cart = $_SESSION['cart'] ?? [];
if (empty($cart)) {
  header("Location: /myukstore/cart.php");
  exit;
}

// Calculate cart total
$ids = implode(',', array_keys($cart));
$stmt = $pdo->query("SELECT * FROM products WHERE id IN ($ids)");
$products = $stmt->fetchAll();

$total = 0;
foreach ($products as $p) {
  $qty = $cart[$p['id']];
  $total += $qty * $p['price'];
}

$errors = [];
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $cardType = trim($_POST['card_type'] ?? '');
  $cardNumber = preg_replace('/\s+/', '', $_POST['card_number'] ?? '');
  $cardName = trim($_POST['card_name'] ?? '');
  $expiryMonth = trim($_POST['expiry_month'] ?? '');
  $expiryYear = trim($_POST['expiry_year'] ?? '');
  $cvv = trim($_POST['cvv'] ?? '');
  
  // Validation
  if (empty($cardType)) {
    $errors[] = "Please select a card type.";
  }
  
  if (empty($cardNumber)) {
    $errors[] = "Card number is required.";
  } elseif (!preg_match('/^\d{16}$/', $cardNumber)) {
    $errors[] = "Card number must be exactly 16 digits.";
  }
  
  if (empty($cardName)) {
    $errors[] = "Cardholder name is required.";
  } elseif (!preg_match('/^[A-Za-z\s]+$/', $cardName)) {
    $errors[] = "Cardholder name must contain only letters.";
  }
  
  if (empty($expiryMonth) || empty($expiryYear)) {
    $errors[] = "Expiry date is required.";
  } else {
    $currentYear = (int)date('Y');
    $currentMonth = (int)date('m');
    $expYear = (int)$expiryYear;
    $expMonth = (int)$expiryMonth;
    
    if ($expYear < $currentYear || ($expYear == $currentYear && $expMonth < $currentMonth)) {
      $errors[] = "Card has expired.";
    }
  }
  
  if (empty($cvv)) {
    $errors[] = "CVV is required.";
  } elseif (!preg_match('/^\d{3,4}$/', $cvv)) {
    $errors[] = "CVV must be 3 or 4 digits.";
  }
  
  // Basic Luhn algorithm check for card number
  if (empty($errors) && !luhnCheck($cardNumber)) {
    $errors[] = "Invalid card number. Please check and try again.";
  }
  
  if (empty($errors)) {
    // Payment successful - clear cart
    unset($_SESSION['cart']);
    $success = true;
  }
}

// Luhn algorithm for card validation
function luhnCheck($number) {
  $sum = 0;
  $numDigits = strlen($number);
  $parity = $numDigits % 2;
  
  for ($i = 0; $i < $numDigits; $i++) {
    $digit = (int)$number[$i];
    if ($i % 2 == $parity) {
      $digit *= 2;
    }
    if ($digit > 9) {
      $digit -= 9;
    }
    $sum += $digit;
  }
  
  return ($sum % 10) == 0;
}

include "includes/header.php";
?>

<div class="checkout-container fade-in-up">
  
  <?php if ($success): ?>
    <div class="alert alert-success d-flex align-items-center">
      <i class="bi bi-check-circle-fill me-2 fs-4"></i>
      <div>
        <strong>Payment Successful!</strong><br>
        Your order has been processed. Thank you for shopping with us!
        <a href="/myukstore/index.php" class="btn btn-dark btn-sm ms-3">Continue Shopping</a>
      </div>
    </div>
  <?php else: ?>
    
    <!-- Order Summary -->
    <div class="order-summary">
      <h4><i class="bi bi-cart-check me-2"></i>Order Summary</h4>
      <?php foreach ($products as $p): 
        $qty = $cart[$p['id']];
        $subtotal = $qty * $p['price'];
      ?>
        <div class="d-flex justify-content-between mb-2">
          <span><?= e($p['title']) ?> × <?= $qty ?></span>
          <span class="fw-bold">£<?= number_format($subtotal, 2) ?></span>
        </div>
      <?php endforeach; ?>
      <div class="order-total">
        Total: £<?= number_format($total, 2) ?>
      </div>
    </div>

    <!-- Error Messages -->
    <?php if (!empty($errors)): ?>
      <div class="alert alert-danger">
        <i class="bi bi-exclamation-triangle-fill me-2"></i>
        <strong>Please correct the following errors:</strong>
        <ul class="mb-0 mt-2">
          <?php foreach ($errors as $error): ?>
            <li><?= e($error) ?></li>
          <?php endforeach; ?>
        </ul>
      </div>
    <?php endif; ?>

    <!-- Payment Form -->
    <div class="payment-card">
      <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="bi bi-credit-card me-2"></i>Payment Details</h2>
        <span class="secure-badge">
          <i class="bi bi-shield-lock-fill"></i>
          Secure Payment
        </span>
      </div>

      <form method="post" id="paymentForm">
        
        <!-- Card Type Selection -->
        <div class="mb-3">
          <label class="form-label">
            <i class="bi bi-credit-card-2-front me-2"></i>Card Type
          </label>
          <select class="form-select" name="card_type" id="cardType" required>
            <option value="">Select Card Type</option>
            <option value="visa">Visa</option>
            <option value="mastercard">MasterCard</option>
            <option value="amex">American Express</option>
          </select>
        </div>

        <!-- Cardholder Name -->
        <div class="mb-3">
          <label class="form-label">
            <i class="bi bi-person me-2"></i>Cardholder Name
          </label>
          <input type="text" 
                 class="form-control" 
                 name="card_name" 
                 id="cardName"
                 placeholder="JOHN SMITH"
                 value="<?= e($_POST['card_name'] ?? '') ?>"
                 pattern="[A-Za-z\s]+"
                 title="Only letters and spaces allowed"
                 required>
          <small class="text-muted">As shown on card</small>
        </div>

        <!-- Card Number -->
        <div class="mb-3">
          <label class="form-label">
            <i class="bi bi-credit-card me-2"></i>Card Number
          </label>
          <input type="text" 
                 class="form-control card-input" 
                 name="card_number" 
                 id="cardNumber"
                 placeholder="1234 5678 9012 3456"
                 maxlength="19"
                 value="<?= e($_POST['card_number'] ?? '') ?>"
                 required>
          <small class="text-muted">16 digits without spaces</small>
        </div>

        <!-- Expiry Date and CVV -->
        <div class="row">
          <div class="col-md-6 mb-3">
            <label class="form-label">
              <i class="bi bi-calendar-event me-2"></i>Expiry Date
            </label>
            <div class="row g-2">
              <div class="col-6">
                <select class="form-select" name="expiry_month" required>
                  <option value="">Month</option>
                  <?php for ($m = 1; $m <= 12; $m++): ?>
                    <option value="<?= sprintf('%02d', $m) ?>" 
                            <?= (isset($_POST['expiry_month']) && $_POST['expiry_month'] == sprintf('%02d', $m)) ? 'selected' : '' ?>>
                      <?= sprintf('%02d', $m) ?>
                    </option>
                  <?php endfor; ?>
                </select>
              </div>
              <div class="col-6">
                <select class="form-select" name="expiry_year" required>
                  <option value="">Year</option>
                  <?php 
                  $currentYear = (int)date('Y');
                  for ($y = $currentYear; $y <= $currentYear + 15; $y++): 
                  ?>
                    <option value="<?= $y ?>" 
                            <?= (isset($_POST['expiry_year']) && $_POST['expiry_year'] == $y) ? 'selected' : '' ?>>
                      <?= $y ?>
                    </option>
                  <?php endfor; ?>
                </select>
              </div>
            </div>
          </div>

          <div class="col-md-6 mb-3">
            <label class="form-label">
              <i class="bi bi-lock me-2"></i>CVV / Security Code
            </label>
            <input type="text" 
                   class="form-control cvv-input" 
                   name="cvv" 
                   id="cvv"
                   placeholder="123"
                   maxlength="4"
                   pattern="\d{3,4}"
                   title="3 or 4 digit security code"
                   value="<?= e($_POST['cvv'] ?? '') ?>"
                   required>
            <small class="text-muted">3 digits on back (4 for Amex)</small>
          </div>
        </div>

        <!-- Terms & Conditions -->
        <div class="mb-3 form-check">
          <input type="checkbox" class="form-check-input" id="terms" required>
          <label class="form-check-label" for="terms">
            I agree to the <a href="#" target="_blank">terms and conditions</a> and <a href="#" target="_blank">privacy policy</a>
          </label>
        </div>

        <!-- Submit Button -->
        <button type="submit" class="btn btn-success w-100 py-3 fs-5">
          <i class="bi bi-lock-fill me-2"></i>
          Pay £<?= number_format($total, 2) ?> Securely
        </button>

        <div class="text-center mt-3">
          <small class="text-muted">
            <i class="bi bi-shield-check me-1"></i>
            Your payment information is encrypted and secure
          </small>
        </div>
      </form>
    </div>

  <?php endif; ?>
</div>

<script>
// Card number formatting
document.getElementById('cardNumber').addEventListener('input', function(e) {
  let value = e.target.value.replace(/\s/g, '');
  value = value.replace(/\D/g, '');
  
  let formattedValue = value.match(/.{1,4}/g)?.join(' ') || value;
  e.target.value = formattedValue;
});

// CVV validation - only numbers
document.getElementById('cvv').addEventListener('input', function(e) {
  e.target.value = e.target.value.replace(/\D/g, '');
});

// Name validation - only letters and spaces
document.getElementById('cardName').addEventListener('input', function(e) {
  e.target.value = e.target.value.replace(/[^A-Za-z\s]/g, '').toUpperCase();
});

// Form submission validation
document.getElementById('paymentForm').addEventListener('submit', function(e) {
  const cardNumber = document.getElementById('cardNumber').value.replace(/\s/g, '');
  
  if (cardNumber.length !== 16) {
    e.preventDefault();
    alert('Card number must be exactly 16 digits');
    return false;
  }
  
  const cvv = document.getElementById('cvv').value;
  if (cvv.length < 3 || cvv.length > 4) {
    e.preventDefault();
    alert('CVV must be 3 or 4 digits');
    return false;
  }
  
  // Show loading state
  const btn = e.target.querySelector('button[type="submit"]');
  btn.disabled = true;
  btn.innerHTML = '<span class="spinner"></span> Processing Payment...';
});
</script>

<?php include "includes/footer.php"; ?>