<?php
// payment.php
require_once 'config.php';

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

require_once 'get_setting.php';

// 1. Get the Tracking Number (Invoice ID) from the URL
$tracking_number = $_GET['invoice'] ?? null;
$shipment = null;
$amount_due = 0.00;
$currency_symbol = '';
$payment_status = '';

// 2. Fetch Shipment Data from the database
if ($tracking_number) {
    try {
        // We select the crucial fields: amount, currency, and payment_status
        $sql = "SELECT id, amount, currency, payment_status, receiver_name 
                FROM shipments 
                WHERE tracking_number = :tracking_number";
        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(':tracking_number', $tracking_number);
        $stmt->execute();
        $shipment = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($shipment) {
            $shipment_id = $shipment['id'];
            $payment_status = $shipment['payment_status'];
            
            // Check if payment is actually due (must not be 'Paid')
            if (strtolower($payment_status) === 'paid') {
                // If Paid, redirect the user with a message
                $_SESSION['alert'] = [
                    'type' => 'success',
                    'title' => 'Payment Status',
                    'text' => 'This invoice has already been successfully paid.',
                ];
                header('Location: index.php');
                exit;
            }

            // Calculate display variables
            $amount_due = number_format((float)$shipment['amount'], 2);
            $invoice_currency = $shipment['currency'] ?? 'USD';
            
            // Simple currency symbol mapping (match the one used in process_shipment.php)
            $currency_symbols = [
                'USD' => '$', 'EUR' => '€', 'GBP' => '£', 'NGN' => '₦', 'CAD' => 'C$'
            ];
            $currency_symbol = $currency_symbols[$invoice_currency] ?? $invoice_currency . ' ';
            
            $header_text = "INVOICE #{$tracking_number}";
            $recipient_name = $shipment['receiver_name'];

        } else {
            // No shipment found for this tracking number
            $header_text = "INVOICE NOT FOUND";
            $_SESSION['alert'] = [
                'type' => 'error',
                'title' => 'Error',
                'text' => 'The requested invoice could not be found.',
            ];
            header('Location: index.php');
            exit;
        }

    } catch (PDOException $e) {
        // Database error
        error_log("Payment Page Error: " . $e->getMessage());
        $_SESSION['alert'] = [
            'type' => 'error',
            'title' => 'System Error',
            'text' => 'A system error occurred while fetching invoice details.',
        ];
        header('Location: index.php');
        exit;
    }
} else {
    // 4. Enforce conditional loading (no 'invoice' parameter in URL)
    $header_text = "ACCESS DENIED";
    $_SESSION['alert'] = [
        'type' => 'warning',
        'title' => 'Missing Invoice ID',
        'text' => 'Please use the link provided in your email to access this payment page.',
    ];
    header('Location: index.php');
    exit;
}

?>
<!DOCTYPE html>
<html lang="en">
   <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title><?php echo $header_text; ?> | <?php echo htmlspecialchars($site_settings['site_title'] ?? 'ReliParcel Express'); ?></title>
     <?php if ($use_favicon): ?>
     <link rel="icon" type="<?php echo $favicon_mime; ?>" href="<?php echo $favicon_path; ?>">
     <?php else: ?>
     <link rel="icon" type="image/x-icon" href="../assets/images/favicon.ico">
     <?php endif; ?>
     <link href="assets/css/style.css" rel="stylesheet">
     <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
     <link rel="stylesheet" href="assets/css/font-awesome-pro.css">
     <link rel="stylesheet" href="assets/css/gtranslate.css">
     <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
     <style>
            .hero-gradient-bg {
                background: linear-gradient(135deg, #b00000, #ffc107);
            }
           
            .clean-draw-btn {background: transparent;border: 2px solid white;color: white;font-weight: 600;font-size: 1.1rem;padding: 14px 26px;border-radius: 8px;letter-spacing: 0.3px;transition: all 0.3s ease;cursor: pointer;}.clean-draw-btn:hover {background: white;color: #1e3c72;transform: translateY(-2px);box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);}.clean-draw-btn:active {transform: translateY(0);}.clean-draw-btn .bi-trophy {font-size: 1.2rem;margin-right: 8px;}.button-showcase {text-align: center;}.button-showcase h2 {color: white;margin-bottom: 30px;font-weight: 300;letter-spacing: 1px;}.btn-skew {transform: skewX(-15deg);padding: 10px 30px !important;border-radius: 5px !important;font-size: 13px;font-weight: 800 !important;transition: transform 0.3s ease, box-shadow 0.3s ease;font-family: 'Work Sans', sans-serif !important;display: inline-block;border: none;}.btn-skew-text {transform: skewX(15deg);display: inline-block;transition: transform 0.3s ease;}.btn-skew:hover {transform: skewX(15deg) scale(1.05);box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);}.btn-skew:hover .btn-skew-text {transform: skewX(-15deg);}@media(max-width:478px) {.clean-draw-btn {font-size: 0.8rem;}}.winner-img-container {position: relative;overflow: hidden;}.winner-verified-badge {position: absolute;top: 10px;right: 10px;z-index: 10;box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);padding: 0.4em 0.8em;font-size: 6px;color: #fff;}#hero-slider-main {position: relative;max-height: 700px;overflow: hidden;}.hero-image {height: 600px;object-fit: cover;filter: brightness(0.85);transition: transform 0.5s ease, filter 0.5s ease;}.carousel-item:hover .hero-image {transform: scale(1.05);filter: brightness(0.75);}.carousel-item {position: relative;}.carousel-caption {position: absolute;top: 0;left: 0;right: 0;bottom: 0;z-index: 10;background: linear-gradient(135deg, rgba(176, 0, 0, 0.3), rgba(0, 0, 0, 0.6));}.hero-caption-box {max-width: 800px;background: rgba(0, 0, 0, 0.3);padding: 3rem !important;border-radius: 0.5rem;backdrop-filter: blur(10px);border: 1px solid rgba(218, 165, 32, 0.3);box-shadow: 0 10px 40px rgba(0, 0, 0, 0.4);animation: fadeInUp 0.8s ease-out;}@keyframes fadeInUp {from {opacity: 0;transform: translateY(30px);}to {opacity: 1;transform: translateY(0);}}.hero-caption-box h1 {text-shadow: 3px 3px 10px rgba(0, 0, 0, 0.8);letter-spacing: 1px;}.hero-caption-box p {text-shadow: 2px 2px 8px rgba(0, 0, 0, 0.7);}.hero-caption-box .btn {transition: all 0.3s ease;border: 2px solid transparent;text-transform: uppercase;letter-spacing: 1px;}.hero-caption-box .btn:hover, .btn-skew-text:hover {transform: skewX(15deg) scale(1.05);border-color: rgba(255, 255, 255, 0.3);}#mainHeroCarousel .carousel-indicators {bottom: 30px;}#mainHeroCarousel .carousel-indicators button {width: 12px;height: 12px;border-radius: 50%;background-color: #daa520;opacity: 0.7;transition: all 0.3s ease;border: 2px solid rgba(255, 255, 255, 0.3);margin: 0 6px;}#mainHeroCarousel .carousel-indicators button:hover {opacity: 0.9;transform: scale(1.2);}#mainHeroCarousel .carousel-indicators .active {background-color: #b00000;opacity: 1;width: 40px;border-radius: 6px;border-color: rgba(255, 255, 255, 0.5);}#mainHeroCarousel .carousel-control-prev-icon, #mainHeroCarousel .carousel-control-next-icon {width: 3rem;height: 3rem;background-color: rgba(176, 0, 0, 0.6);border-radius: 50%;transition: all 0.3s ease;border: 2px solid rgba(218, 165, 32, 0.4);}#mainHeroCarousel .carousel-control-prev-icon:hover, #mainHeroCarousel .carousel-control-next-icon:hover {background-color: rgba(176, 0, 0, 0.9);border-color: #daa520;transform: scale(1.1);}#mainHeroCarousel .carousel-control-prev, #mainHeroCarousel .carousel-control-next {opacity: 0.7;transition: opacity 0.3s ease;}#mainHeroCarousel .carousel-control-prev:hover, #mainHeroCarousel .carousel-control-next:hover {opacity: 1;}@media (max-width: 768px) {.hero-image {height: 500px;}.hero-caption-box {padding: 2rem !important;}.hero-caption-box h1 {font-size: 21px !important;}}#typeText::after {content: '|';animation: blink 0.7s infinite;color: goldenrod;}@keyframes blink {50% {opacity: 0;}}
          @media (max-width:470px){
          .hero-caption-box p{
          font-size:14px !important;
          }
         .winner-img{height: 250px;}
          }
         .winner-img {width: 100%; display: block; height: 300px; object-position: center center;}
     </style>
   </head>
   <body>
      <?php include "nav.php" ?>
      <?php
          
          if (isset($_SESSION['alert'])) {
              $alert = $_SESSION['alert'];
              
              unset($_SESSION['alert']);
          
              
              echo "<script>
                  document.addEventListener('DOMContentLoaded', function() {
                      Swal.fire({
                          icon: '{$alert['type']}',
                          title: '{$alert['title']}',
                          text: '{$alert['text']}',
                          confirmButtonColor: '#b00000', // Adjust to your crimson color
                      });
                  });
              </script>";
          }
          ?>
      <header class="hero-gradient-bg text-white text-center pt-5 pb-6 shadow-lg">
    <div class="container mt-5 pt-5" style="padding-bottom:100px;">
        <h1 class="display-6 fw-bolder mb-3">
            <?php echo $header_text; ?>
        </h1>
        <p class="lead mb-2 fs-5">Shipment for **<?php echo htmlspecialchars($recipient_name ?? 'Recipient'); ?>**</p>
        <h2 class="fw-bolder mb-3" style="color: #FFC107;">
            TOTAL DUE: <?php echo $currency_symbol . $amount_due; ?>
        </h2>
        <p class="lead mb-5 fs-5">Kindly proceed with payment to confirm your shipment.</p>
        <div class="mt-2">
            <a href="index.php" class="btn btn-outline-light rounded-pill px-4 fw-bold">
                <i class="bi bi-house-door-fill me-2"></i> BACK TO HOME
            </a>
        </div>
    </div>
</header>


      <section class="py-5 bg-light">
          <div class="container">
             <div class="mx-auto text-center" style="max-width: 600px;">
                <h2 class="fw-bolder mb-1 text-dark">SECURE PAYMENT OPTIONS</h2>
             </div>
             <p class="text-center text-muted mb-4">All transactions are handled safely, ensuring your information stays secure.</p>
             <div class="row justify-content-center">
                <div class="col-12 text-center">
                  <div class="d-grid gap-2 d-sm-flex justify-content-sm-center flex-column" style="max-width: 300px; margin: 0 auto;">
                     <?php if ($bank_enabled): ?>
                     <a class="btn btn-md btn-bank-transfer rounded-pill" href="#bankDetailsModal" data-bs-toggle="modal">
                     <i class="fas fa-university me-2"></i> Bank Transfer
                     </a>
                     <?php endif; ?>
                     <?php if ($crypto_enabled): ?>
                     <a class="btn btn-md btn-crypto-payments rounded-pill" href="#cryptoDetailsModal" data-bs-toggle="modal">
                     <i class="fab fa-btc me-2"></i> Crypto Payments
                     </a>
                     <?php endif; ?>
                     <?php if ($giftcard_enabled): ?>
                     <a class="btn btn-md btn-gift-cards rounded-pill" href="#giftcardDetailsModal" data-bs-toggle="modal">
                     <i class="fas fa-gift me-2"></i> Gift Cards
                     </a>
                     <?php endif; ?>
                     <?php if (!$bank_enabled && !$crypto_enabled && !$giftcard_enabled): ?>
                     <p class="text-danger lead">No active payment methods found.</p>
                     <?php endif; ?>
                  </div>
                </div>
             </div>
          </div>
      </section>

      <section class="py-5 bg-white border-top">
          <div class="container">
              <div class="mx-auto text-center mb-5" style="max-width: 600px;">
                  <h2 class="fw-bolder mb-1 text-dark">PAYMENT ROADMAP</h2>
                  <p class="text-muted">A simple 4-step process to get your shipment moving.</p>
              </div>
              
              <div class="row g-4 justify-content-center">
                  <div class="col-lg-3 col-md-6">
                      <div class="text-center p-4 h-100">
                          <div class="mb-3">
                              <span class="d-inline-flex align-items-center justify-content-center bg-danger text-white rounded-circle shadow-sm" style="width: 60px; height: 60px;">
                                  <i class="bi bi-1-circle-fill fs-3"></i>
                              </span>
                          </div>
                          <h5>Select Method</h5>
                          <p class="small text-muted">Choose between Bank Transfer, Crypto, or Gift Cards above.</p>
                      </div>
                  </div>
                  <div class="col-lg-3 col-md-6">
                      <div class="text-center p-4 h-100">
                          <div class="mb-3">
                              <span class="d-inline-flex align-items-center justify-content-center bg-danger text-white rounded-circle shadow-sm" style="width: 60px; height: 60px;">
                                  <i class="bi bi-2-circle-fill fs-3"></i>
                              </span>
                          </div>
                          <h5>Make Payment</h5>
                          <p class="small text-muted">Follow the specific instructions provided in the payment modal.</p>
                      </div>
                  </div>
                  <div class="col-lg-3 col-md-6">
                      <div class="text-center p-4 h-100">
                          <div class="mb-3">
                              <span class="d-inline-flex align-items-center justify-content-center bg-danger text-white rounded-circle shadow-sm" style="width: 60px; height: 60px;">
                                  <i class="bi bi-3-circle-fill fs-3"></i>
                              </span>
                          </div>
                          <h5>Verify Proof</h5>
                          <p class="small text-muted">Submit your receipt or screenshot to our agents for rapid verification.</p>
                      </div>
                  </div>
                  <div class="col-lg-3 col-md-6">
                      <div class="text-center p-4 h-100">
                          <div class="mb-3">
                              <span class="d-inline-flex align-items-center justify-content-center bg-success text-white rounded-circle shadow-sm" style="width: 60px; height: 60px;">
                                  <i class="bi bi-check-circle-fill fs-3"></i>
                              </span>
                          </div>
                          <h5>Shipment Release</h5>
                          <p class="small text-muted">Once confirmed, your shipment instantly proceeds to the next dispatch phase.</p>
                      </div>
                  </div>
              </div>
          </div>
      </section>
      
      <?php include "include/payment_modals.php" ?>
      <?php include "footer.php" ?>
      <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
      
      
       <?php include "custom_script.php" ?>
   </body>
</html>