<?php
require __DIR__ . '/includes/functions.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: checkout.php');
    exit;
}

$errors = array();

if (!verify_csrf_token((string) (isset($_POST['csrf_token']) ? $_POST['csrf_token'] : ''))) {
    $errors[] = 'Security token expired or invalid. Please go back to checkout and submit again.';
}

$name = clean_text((string) (isset($_POST['name']) ? $_POST['name'] : ''), 120);
$phone = clean_text((string) (isset($_POST['phone']) ? $_POST['phone'] : ''), 30);
$email = clean_text((string) (isset($_POST['email']) ? $_POST['email'] : ''), 160);
$city = clean_text((string) (isset($_POST['city']) ? $_POST['city'] : ''), 120);
$address = clean_text((string) (isset($_POST['address']) ? $_POST['address'] : ''), 220);
$paymentMethod = clean_text((string) (isset($_POST['payment_method']) ? $_POST['payment_method'] : ''), 80);
$deliveryMethod = clean_text((string) (isset($_POST['delivery_method']) ? $_POST['delivery_method'] : ''), 80);
$paymentReference = clean_text((string) (isset($_POST['payment_reference']) ? $_POST['payment_reference'] : ''), 140);
$rawMessage = trim((string) (isset($_POST['message']) ? $_POST['message'] : ''));
$message = function_exists('mb_substr') ? mb_substr($rawMessage, 0, 1000) : substr($rawMessage, 0, 1000);
$items = normalize_cart_payload((string) (isset($_POST['order_payload']) ? $_POST['order_payload'] : '[]'));
$total = order_total($items);

$allowedPayments = array_keys(payment_method_options());
$allowedDeliveries = array('Home Delivery', 'Store Pickup', 'Branch Delivery');

if (strlen($name) < 2) {
    $errors[] = 'Full name is required.';
}

if (!preg_match('/^[0-9+()\-\s]{7,30}$/', $phone)) {
    $errors[] = 'Please enter a valid mobile number.';
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = 'Please enter a valid email address.';
}

if (strlen($city) < 2) {
    $errors[] = 'City or municipality is required.';
}

if (strlen($address) < 5) {
    $errors[] = 'Delivery address is required.';
}

if (!in_array($paymentMethod, $allowedPayments, true)) {
    $errors[] = 'Please select a valid payment method.';
}

if (!in_array($deliveryMethod, $allowedDeliveries, true)) {
    $errors[] = 'Please select a valid delivery preference.';
}

if (!$items) {
    $errors[] = 'Your cart is empty or contains invalid products.';
}

$proofUpload = save_uploaded_payment_proof(isset($_FILES['payment_proof']) ? $_FILES['payment_proof'] : null);
if (!$proofUpload['ok']) {
    $errors[] = $proofUpload['error'];
}
$proofPath = $proofUpload['path'];
$paymentStatus = initial_payment_status($paymentMethod, $proofPath);
$payments = payment_settings();
$onlineCheckout = array_get($payments, 'online_checkout', array());
$paymentLink = '';
if ($paymentMethod === 'Credit/Debit Card Payment Link' && is_array($onlineCheckout) && array_get($onlineCheckout, 'enabled', false)) {
    $paymentLink = trim((string) array_get($onlineCheckout, 'payment_link', ''));
}

$currentPage = 'cart';
$pageTitle = $errors ? 'Checkout Error | Furnify' : 'Request Sent | Furnify';

if ($errors) {
    require __DIR__ . '/includes/header.php';
    ?>
    <section class="page-section">
        <div class="container narrow">
            <div class="confirmation error-state">
                <i class="bi bi-exclamation-triangle" aria-hidden="true"></i>
                <p class="eyebrow">Please review</p>
                <h1>Hindi pa na-submit ang request.</h1>
                <p class="lead">May kailangang ayusin bago maisave ang order/payment summary.</p>
                <ul class="error-list">
                    <?php foreach ($errors as $error): ?>
                        <li><?= e($error) ?></li>
                    <?php endforeach; ?>
                </ul>
                <a href="checkout.php" class="btn btn-primary mt-3">Back to Checkout</a>
            </div>
        </div>
    </section>
    <?php
    require __DIR__ . '/includes/footer.php';
    exit;
}

$orderNumber = generate_order_number();
$customerAccount = customer_current();
$order = array(
    'customer_id' => $customerAccount ? (int) $customerAccount['id'] : null,
    'order_number' => $orderNumber,
    'created_at' => date('c'),
    'customer' => array(
        'name' => $name,
        'phone' => $phone,
        'email' => $email,
        'city' => $city,
        'address' => $address,
    ),
    'preferences' => array(
        'payment_method' => $paymentMethod,
        'delivery_method' => $deliveryMethod,
        'message' => $message,
    ),
    'payment' => array(
        'status' => $paymentStatus,
        'reference' => $paymentReference,
        'proof_path' => $proofPath,
        'payment_link' => $paymentLink,
        'amount_paid' => 0,
        'balance_due' => $total,
    ),
    'items' => $items,
    'total' => $total,
    'status' => 'Pending quotation',
);

$saved = save_order($order);
$manualGcash = array_get($payments, 'manual_gcash', array());

require __DIR__ . '/includes/header.php';
?>

<section class="page-section">
    <div class="container narrow">
        <div class="confirmation">
            <i class="bi bi-check-circle" aria-hidden="true"></i>
            <p class="eyebrow">Request received</p>
            <h1>Salamat, <?= e($name) ?>.</h1>
            <p class="lead">Your Furnify request has been saved. Product totals were recalculated from the server catalog.</p>
            <div class="order-number-card">
                <span>Order reference</span>
                <strong><?= e($orderNumber) ?></strong>
            </div>
            <?php if (!$saved): ?>
                <div class="alert alert-warning mt-3">Request displayed successfully, but the server could not write to MySQL or <code>storage/orders</code>. Please check database/folder permission.</div>
            <?php endif; ?>

            <div class="payment-result-card mt-4">
                <div>
                    <span>Payment method</span>
                    <strong><?= e($paymentMethod) ?></strong>
                </div>
                <div>
                    <span>Payment status</span>
                    <strong><?= e($paymentStatus) ?></strong>
                </div>
                <?php if ($paymentReference !== ''): ?>
                    <div><span>Reference no.</span><strong><?= e($paymentReference) ?></strong></div>
                <?php endif; ?>
                <?php if ($proofPath !== ''): ?>
                    <div><span>Proof uploaded</span><strong>For admin verification</strong></div>
                <?php endif; ?>
            </div>

            <?php if ($paymentMethod === 'GCash Manual' && is_array($manualGcash) && array_get($manualGcash, 'enabled', false)): ?>
                <div class="alert alert-info mt-3 text-start">
                    <strong>GCash details:</strong><br>
                    Name: <?= e(array_get($manualGcash, 'account_name', 'Furnify')) ?><br>
                    Number: <?= e(array_get($manualGcash, 'mobile_number', 'Set in data/settings.php')) ?><br>
                    <?= e(array_get($manualGcash, 'instructions', 'Upload your GCash proof for verification.')) ?>
                </div>
            <?php elseif ($paymentMethod === 'Credit/Debit Card Payment Link'): ?>
                <div class="alert alert-info mt-3 text-start">
                    <strong>Card payment:</strong> Admin will confirm availability/final quote and send a secure payment link. Do not send card numbers through chat or this website.
                    <?php if ($paymentLink !== ''): ?>
                        <div class="mt-2"><a class="btn btn-sm btn-primary" href="<?= e($paymentLink) ?>" target="_blank" rel="noopener">Open secure payment link</a></div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>

            <dl class="confirmation-list">
                <div><dt>Contact</dt><dd><?= e($phone) ?> | <?= e($email) ?></dd></div>
                <div><dt>Delivery</dt><dd><?= e($deliveryMethod) ?> — <?= e($city) ?></dd></div>
                <div><dt>Address</dt><dd><?= e($address) ?></dd></div>
                <div><dt>Estimated subtotal</dt><dd><?= money($total) ?></dd></div>
                <?php if ($message): ?>
                    <div><dt>Notes</dt><dd><?= nl2br(e($message)) ?></dd></div>
                <?php endif; ?>
            </dl>
            <div class="submitted-items">
                <?php foreach ($items as $item): ?>
                    <div>
                        <span><?= e($item['name']) ?></span>
                        <strong><?= (int) $item['qty'] ?> x <?= money($item['price']) ?></strong>
                    </div>
                <?php endforeach; ?>
            </div>
            <div class="d-flex flex-wrap gap-2 mt-4">
                <a href="index.php#catalog" class="btn btn-primary">Back to Store</a>
                <a href="cart.php" class="btn btn-outline-primary">View Cart</a>
            </div>
        </div>
    </div>
</section>

<script>
    localStorage.removeItem('sofaStoreCart');
</script>

<?php require __DIR__ . '/includes/footer.php'; ?>
