<?php
/**
 * Pro Checkout with Voucher System & Sketpay Integration
 */
require_once 'includes/db.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: login");
    exit;
}

// Fetch Logged-in User Data
$user_id = $_SESSION['user_id'];
$stmt_u = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt_u->execute([$user_id]);
$user = $stmt_u->fetch();

// Check if checkout items are set (from cart page)
if (empty($_SESSION['checkout_items'])) {
    // If not set, try to use cart items if they exist
    if (!empty($_SESSION['cart'])) {
        $_SESSION['checkout_items'] = $_SESSION['cart'];
    } else {
        header("Location: cart");
        exit;
    }
}

$checkout_items = $_SESSION['checkout_items'];
$success_msg = ''; 
$error_msg = '';

// Fetch cart items
$placeholders = implode(',', array_fill(0, count($checkout_items), '?'));
$stmt = $pdo->prepare("SELECT * FROM products WHERE id IN ($placeholders)");
$stmt->execute($checkout_items);
$cart_items = $stmt->fetchAll();

// If no valid items found, redirect to cart
if (empty($cart_items)) {
    $_SESSION['checkout_items'] = [];
    header("Location: cart");
    exit;
}

$subtotal = 0;
foreach ($cart_items as $item) { 
    $subtotal += $item['price']; 
}

// Ensure payment settings table exists
$pdo->exec("CREATE TABLE IF NOT EXISTS payment_settings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    base_url VARCHAR(255) NULL,
    api_key VARCHAR(255) NULL
)");

$stmt_check_pay = $pdo->query("SELECT COUNT(*) FROM payment_settings");
if ($stmt_check_pay->fetchColumn() == 0) {
    $pdo->exec("INSERT INTO payment_settings (api_key, base_url) VALUES (NULL, NULL)");
}

// Handle Coupon Application
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['apply_coupon'])) {
    $code = strtoupper(trim($_POST['coupon_code']));
    
    // Check if coupons table exists, if not create it temporarily or handle gracefully
    try {
        $stmt_check_coupon_table = $pdo->query("SHOW TABLES LIKE 'coupons'");
        if($stmt_check_coupon_table->rowCount() == 0) {
             $pdo->exec("CREATE TABLE IF NOT EXISTS coupons (
                id INT AUTO_INCREMENT PRIMARY KEY,
                code VARCHAR(50) NOT NULL UNIQUE,
                discount_value DECIMAL(10,2) NOT NULL,
                is_percentage BOOLEAN DEFAULT 0,
                status ENUM('active', 'inactive') DEFAULT 'active',
                valid_until DATE NOT NULL
            )");
        }

        $stmt_c = $pdo->prepare("SELECT * FROM coupons WHERE code = ? AND status = 'active' AND valid_until >= CURDATE()");
        $stmt_c->execute([$code]);
        $coupon = $stmt_c->fetch();

        if ($coupon) {
            $_SESSION['applied_coupon'] = $coupon;
            $success_msg = "Coupon applied successfully!";
        } else {
            $error_msg = "Invalid or expired coupon code.";
        }
    } catch (Exception $e) {
         $error_msg = "Coupon system is currently unavailable.";
    }
}

// Calculate Final Price
$discount_amount = 0;
$coupon_code = $_SESSION['applied_coupon']['code'] ?? '';

if (isset($_SESSION['applied_coupon'])) {
    $cp = $_SESSION['applied_coupon'];
    if ($cp['is_percentage']) {
        $discount_amount = ($subtotal * $cp['discount_value']) / 100;
    } else {
        $discount_amount = $cp['discount_value'];
    }
}
$final_payable = max(0, $subtotal - $discount_amount);

// Handle Payment Processing
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['proceed_to_pay'])) {
    
    $invoice_no = 'INV-' . strtoupper(uniqid()); 
    $cus_name = $user['name'] ?? 'Customer';
    $cus_email = $user['email'] ?? 'customer@example.com';
    
    $pdo->beginTransaction();
    try {
        // Insert orders
        foreach ($cart_items as $item) {
            $stmt_order = $pdo->prepare("INSERT INTO orders (invoice_no, user_id, product_id, amount, payment_method, status) VALUES (?, ?, ?, ?, 'Sketpay', 'pending')");
            $stmt_order->execute([$invoice_no, $user_id, $item['id'], $item['price']]);
        }
        
        // Fetch payment settings
        $stmt_pay = $pdo->query("SELECT * FROM payment_settings LIMIT 1");
        $pay_settings = $stmt_pay->fetch();
        
        $base_url = rtrim($pay_settings['base_url'] ?? '', '/');
        $api_key = trim($pay_settings['api_key'] ?? '');
        
        if(empty($api_key) || empty($base_url)) {
            throw new Exception("Payment Gateway configuration is missing. Please contact administrator.");
        }

        // Construct URLs
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
        $host = trim($_SERVER['HTTP_HOST']);
        $dir = str_replace('\\', '/', dirname($_SERVER['PHP_SELF']));
        $base_domain = rtrim($protocol . "://" . $host . $dir, '/');
        
        $success_url = $base_domain . "/success";
        $cancel_url = $base_domain . "/checkout";
        $webhook_url = $base_domain . "/webhook.php";
        
        $_SESSION['checkout_invoice'] = $invoice_no;

        // Prepare Payload
        $payload_array = array(
            "cus_name" => $cus_name,
            "cus_email" => $cus_email,
            "amount" => (string)(float)$final_payable,
            "success_url" => $success_url,
            "cancel_url" => $cancel_url,
            "webhook_url" => $webhook_url,
            "metadata" => array("payment_id" => $invoice_no)
        );

        $payload = json_encode($payload_array, JSON_UNESCAPED_SLASHES);

        // cURL Request to Sketpay
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $base_url . '/api/payment/create',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_HTTPHEADER => array(
                'API-KEY: ' . $api_key,
                'Content-Type: application/json'
            ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);

        if ($err) { throw new Exception("Payment Gateway Error: " . $err); }

        $res = json_decode($response, true);
        $redirect_url = $res['payment_url'] ?? $res['url'] ?? $res['data']['url'] ?? '';

        if (empty($redirect_url)) {
            throw new Exception("Gateway Response Error: " . ($res['message'] ?? 'Unknown Error'));
        }

        // Clear checkout items on success initialization
        $_SESSION['checkout_items'] = [];
        
        // Remove purchased items from cart if they were there
        if(!empty($_SESSION['cart'])){
            $_SESSION['cart'] = array_diff($_SESSION['cart'], array_column($cart_items, 'id'));
            $_SESSION['cart'] = array_values($_SESSION['cart']);
        }
        
        // Clear coupon
        unset($_SESSION['applied_coupon']);

        $pdo->commit();
        header("Location: " . $redirect_url);
        exit;
        
    } catch (Exception $e) {
        $pdo->rollBack();
        $error_msg = $e->getMessage();
    }
}

$page_title = 'Secure Checkout';
require_once 'includes/header.php';
?>

<style>
    @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&family=Noto+Serif+Bengali:wght@300;400;500;600;700&display=swap');

    body {
        font-family: 'Roboto', 'Noto Serif Bengali', sans-serif !important;
        background-color: #f8fafc;
        margin: 0; padding: 0;
    }

    .checkout-wrapper {
        max-width: 1200px;
        margin: 20px auto 100px;
        padding: 0 10px; 
    }

    .checkout-layout { 
        display: grid; 
        grid-template-columns: 1fr 400px; /* Swapped DOM order below, but keeping grid columns relative */
        gap: 20px; 
        align-items: start;
    }

    .card-white { 
        background: #fff; border-radius: 8px; padding: 25px; 
        border: 1px solid #e2e8f0; 
    }

    .checkout-section-title {
        font-size: 1.15rem; font-weight: 700; color: #0f172a;
        margin-bottom: 15px; text-transform: uppercase;
    }

    /* Tabs for Billing/Info */
    .checkout-tabs {
        display: flex; border-bottom: 1px solid #e2e8f0; margin-bottom: 20px; gap: 20px;
    }
    .tab-item {
        padding: 10px 0; font-weight: 600; color: #64748b; cursor: pointer; border-bottom: 2px solid transparent;
    }
    .tab-item.active { color: #00059E; border-bottom-color: #00059E; }

    .form-group { margin-bottom: 15px; }
    .form-group label { display: block; font-weight: 500; margin-bottom: 6px; font-size: 0.9rem; color: #475569; }
    .form-control {
        width: 100%; padding: 10px 12px; border: 1px solid #cbd5e1; border-radius: 4px;
        font-family: 'Roboto', sans-serif; font-size: 0.95rem; box-sizing: border-box; background: #f1f5f9; cursor: not-allowed;
    }
    
    .form-control:focus { outline: none; }
    
    textarea.form-control { background: #fff; cursor: text; }

    /* Coupon */
    .coupon-box { margin-bottom: 20px; padding: 15px; background: #fff; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 0.95rem; color: #334155; }
    .coupon-toggle { color: #00059E; cursor: pointer; font-weight: 600; font-size: 0.9rem; }
    .coupon-form { display: none; margin-top: 10px; }
    .coupon-form.active { display: flex; gap: 8px; }

    /* Order Summary */
    .order-table { width: 100%; border-collapse: collapse; font-size: 0.95rem; }
    .order-table td { padding: 15px 0; border-bottom: 1px solid #f1f5f9; color: #475569; }
    .order-table th { text-align: left; padding-bottom: 10px; border-bottom: 2px solid #e2e8f0; color: #0f172a; }
    
    .product-cell { display: flex; align-items: center; gap: 12px; }
    .product-cell img { width: 50px; height: 50px; object-fit: cover; border-radius: 6px; border: 1px solid #f1f5f9; }
    .product-cell div { color: #334155; font-weight: 500; }

    .total-row td { font-size: 1.25rem; font-weight: 700; color: #00059E; border: none; padding-top: 20px; }

    .payment-box { margin-top: 20px; padding: 20px; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 6px; }
    
    .btn-place-order { 
        width: 100%; background: #00059E; color: #fff; padding: 16px; border-radius: 6px; 
        border: none; font-size: 1.1rem; font-weight: 700; cursor: pointer; transition: 0.3s; margin-top: 15px;
    }
    .btn-place-order:hover { background: #00037a; }

    /* Toast Full Fill + Fade Animation */
    .toast-container { position: fixed; top: 20px; right: 20px; z-index: 9999; display: flex; flex-direction: column; gap: 10px; pointer-events: none; }
    .toast {
        min-width: 250px; padding: 16px 20px; border-radius: 8px; color: #fff; display: flex; align-items: center; gap: 12px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15); opacity: 0; transition: opacity 0.4s ease; font-weight: 500; font-size: 0.95rem;
        position: relative; overflow: hidden; border: none;
    }
    .toast.show { opacity: 1; }
    .toast-success { background-color: #10b981; }
    .toast-error { background-color: #ef4444; }
    
    .toast-progress {
        position: absolute; bottom: 0; left: 0; height: 4px; background: rgba(255,255,255,0.7);
        width: 100%; animation: toastProgress 3s linear forwards;
    }
    
    @keyframes toastProgress {
        100% { width: 0; }
    }

    @media (max-width: 992px) { 
        .checkout-layout { grid-template-columns: 1fr; } 
    }
</style>

<div id="toast-container" class="toast-container"></div>

<div class="checkout-wrapper">
    <div class="coupon-box">
        Have a coupon? <span class="coupon-toggle" onclick="document.getElementById('couponForm').classList.toggle('active')">Click here to enter your code</span>
        <form action="" method="POST" class="coupon-form" id="couponForm">
            <input type="text" name="coupon_code" class="form-control" style="background:#fff; cursor:text;" placeholder="Coupon code" value="<?php echo htmlspecialchars($coupon_code); ?>" required>
            <button type="submit" name="apply_coupon" style="background:#0f172a; color:#fff; border:none; padding:0 20px; border-radius:4px; cursor:pointer; font-weight:500;">APPLY</button>
        </form>
    </div>

    <div class="checkout-layout">
        
        <div>
            <div class="card-white" style="border: 2px dashed #e2e8f0; background: #fafafa;">
                <h2 class="checkout-section-title" style="text-align:center;">YOUR ORDER</h2>
                <table class="order-table">
                    <thead>
                        <tr>
                            <th>PRODUCT</th>
                            <th style="text-align:right;">SUBTOTAL</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($cart_items as $item): ?>
                        <tr>
                            <td class="product-cell">
                                <img src="<?php echo get_image_url('products/images', $item['main_image']); ?>" alt="Product">
                                <div><?php echo htmlspecialchars($item['title']); ?> <span style="color:#64748b; font-weight:400;">× 1</span></div>
                            </td>
                            <td style="text-align:right; font-weight:500;"><?php echo (defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : '৳') . number_format($item['price'], 2); ?></td>
                        </tr>
                        <?php endforeach; ?>
                        
                        <tr>
                            <td style="font-weight:600; color:#0f172a;">Subtotal</td>
                            <td style="text-align:right; font-weight:600; color:#00059E;"><?php echo (defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : '৳') . number_format($subtotal, 2); ?></td>
                        </tr>
                        
                        <?php if($discount_amount > 0): ?>
                        <tr style="color:#10b981;">
                            <td>Discount</td>
                            <td style="text-align:right;">- <?php echo (defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : '৳') . number_format($discount_amount, 2); ?></td>
                        </tr>
                        <?php endif; ?>
                        
                        <tr class="total-row">
                            <td>Total</td>
                            <td style="text-align:right;"><?php echo (defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : '৳') . number_format($final_payable, 2); ?></td>
                        </tr>
                    </tbody>
                </table>

                <div class="payment-box">
                    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:15px;">
                        <span style="font-weight:600; font-size:0.95rem; color:#475569;">Pay via Sketpay</span>
                        <img src="https://i.supaimg.com/d25ec2bf-78c6-492d-a44f-f0d52090f6c0/a6919cbd-3639-4223-8455-84bd9a90b194.png" style="height:25px;">
                    </div>
                    
                    <div style="background:#fff; padding:15px; border:1px solid #e2e8f0; border-radius:4px; font-size:0.85rem; color:#64748b; line-height:1.5;">
                        এখানে অটো পেমেন্ট হবে সাথে সাথে zip পেয়ে যাবেন কোনো সমস্যা হলে Contacts. এ ক্লিক করে আমাদের মেসেজ করুন
                    </div>

                    <p style="font-size:0.8rem; color:#64748b; margin-top:20px; line-height:1.5;">
                        Your personal data will be used to process your order, support your experience throughout this website, and for other purposes described in our <strong>privacy policy</strong>.
                    </p>
                    
                    <form action="" method="POST">
                        <button type="submit" name="proceed_to_pay" class="btn-place-order">PLACE ORDER</button>
                    </form>
                </div>
            </div>
        </div>

        <div>
            <div class="card-white">
                <div class="checkout-tabs">
                    <div class="tab-item active">BILLING DETAILS</div>
                </div>
                
                <div class="form-group">
                    <label>First Name <span style="color:#ef4444;">*</span></label>
                    <input type="text" class="form-control" value="<?php echo htmlspecialchars($user['name']); ?>" disabled>
                </div>
                <div class="form-group">
                    <label>Email Address <span style="color:#ef4444;">*</span></label>
                    <input type="text" class="form-control" value="<?php echo htmlspecialchars($user['email']); ?>" disabled>
                </div>
                <div class="form-group">
                    <label>Country <span style="color:#ef4444;">*</span></label>
                    <div style="font-size:0.95rem; color:#475569; padding-top:5px;">Bangladesh</div>
                </div>
                
                <h3 style="font-size: 1.15rem; margin: 30px 0 15px 0; color:#0f172a;">ADDITIONAL INFORMATION</h3>
                <div class="form-group">
                    <label>Order notes (optional)</label>
                    <textarea class="form-control" rows="4" placeholder="Notes about your order, e.g. special notes for delivery."></textarea>
                </div>
            </div>
        </div>

    </div>
</div>

<script>
    function showToast(message, type) {
        const container = document.getElementById('toast-container');
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        
        let iconHtml = '';
        if(type === 'success') {
            iconHtml = `<svg width="24" height="24" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>`;
        } else {
            iconHtml = `<svg width="24" height="24" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>`;
        }
        
        toast.innerHTML = `${iconHtml} <span>${message}</span> <div class="toast-progress"></div>`;
        container.appendChild(toast);
        
        // Trigger reflow to restart animation
        void toast.offsetWidth;
        toast.classList.add('show');
        
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => {
                toast.remove();
            }, 400); // Wait for fade out
        }, 3000);
    }

    <?php if($success_msg): ?>
        showToast("<?php echo addslashes($success_msg); ?>", "success");
    <?php endif; ?>
    <?php if($error_msg): ?>
        showToast("<?php echo addslashes($error_msg); ?>", "error");
    <?php endif; ?>
</script>

<?php require_once 'includes/footer.php'; ?>
<?php require_once 'includes/mobile-nav.php'; ?>
