<?php
require_once '../includes/User.php';
require_once '../includes/cart.php';
require_once '../includes/db_config.php';
require_once '../includes/session_helper.php';
require_once '../includes/pricing.php';

safe_session_start();

if (!User::isLoggedIn()) {
    header("Location: /allura/login.php");
    exit();
}

if (isset($_GET['success']) && isset($_SESSION['order_success'])) {
    $order_data = $_SESSION['order_success'];
    $subscription_data = isset($_SESSION['subscription_created']) ? $_SESSION['subscription_created'] : null;
    unset($_SESSION['order_success']); 
    unset($_SESSION['subscription_created']);
    $me = User::getCurrentUser();
    
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Order Confirmed - Allura Dry Clean</title>
        <link rel="stylesheet" href="/allura/css/style.css">
        <?php include '../includes/header.php'; ?>
 
    </head>
    <body>
        <div class="success-container">
            <div class="success-card">
                <div class="success-icon">
                    ✓
                </div>
                
                <h1 class="success-title">Order Confirmed!</h1>
                
                <p class="success-message">
                    Thank you, <?php echo htmlspecialchars($me['name']); ?>! Your order has been successfully placed and is being processed.
                </p>
                
                 <div class="order-details">
                     <div class="detail-row">
                         <span class="detail-label">Order ID:</span>
                         <span class="detail-value">#<?php echo str_pad($order_data['order_id'], 6, '0', STR_PAD_LEFT); ?></span>
                     </div>
                     <div class="detail-row">
                         <span class="detail-label">Subtotal:</span>
                         <span class="detail-value">SAR <?php echo number_format($order_data['subtotal'], 2); ?></span>
                     </div>
                     <?php if ($order_data['discount_amount'] > 0): ?>
                     <div class="detail-row" style="color: #28a745;">
                         <span class="detail-label">Discount (<?php echo htmlspecialchars($order_data['discount_title']); ?>):</span>
                         <span class="detail-value">-SAR <?php echo number_format($order_data['discount_amount'], 2); ?></span>
                     </div>
                     <?php endif; ?>
                     <div class="detail-row">
                         <span class="detail-label">Tax (8%):</span>
                         <span class="detail-value">SAR <?php echo number_format($order_data['tax_amount'], 2); ?></span>
                     </div>
                     <div class="detail-row">
                         <span class="detail-label">Delivery Date:</span>
                         <span class="detail-value"><?php echo date('F j, Y', strtotime($order_data['delivery_date'])); ?></span>
                     </div>
                     <div class="detail-row">
                         <span class="detail-label">Payment Method:</span>
                         <span class="detail-value"><?php echo ucfirst(str_replace('_', ' ', $order_data['payment_method'])); ?></span>
                     </div>
                     <div class="detail-row">
                         <span class="detail-label">Total Amount:</span>
                         <span class="detail-value">SAR <?php echo number_format($order_data['total_amount'], 2); ?></span>
                     </div>
                 </div>
                
                <?php if ($subscription_data): ?>
                <div class="subscription-info" style="background: linear-gradient(135deg, #e8f5e8 0%, #c8e6c9 100%); padding: 1.5rem; border-radius: 10px; margin: 1.5rem 0; border: 2px solid #4caf50; box-shadow: 0 4px 15px rgba(76,175,80,0.2);">
                    <h4 style="color: #2e7d32; margin: 0 0 1rem 0; display: flex; align-items: center;">
                        <span style="font-size: 1.5rem; margin-right: 0.5rem;"></span>
                        Subscription Activated!
                    </h4>
                    <?php foreach ($subscription_data as $subscription): ?>
                    <div style="background: white; padding: 1rem; border-radius: 8px; margin-bottom: 0.5rem; border-left: 4px solid #4caf50;">
                        <div class="detail-row">
                            <span class="detail-label">Plan:</span>
                            <span class="detail-value" style="color: #2e7d32; font-weight: bold;"><?php echo htmlspecialchars($subscription['plan_name']); ?></span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">Type:</span>
                            <span class="detail-value"><?php echo ucfirst($subscription['plan_type']); ?></span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">Valid From:</span>
                            <span class="detail-value"><?php echo date('F j, Y', strtotime($subscription['start_date'])); ?></span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">Valid Until:</span>
                            <span class="detail-value"><?php echo date('F j, Y', strtotime($subscription['end_date'])); ?></span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">Usage Limit:</span>
                            <span class="detail-value"><?php echo $subscription['max_usage']; ?> orders</span>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    <p style="margin: 1rem 0 0 0; color: #2e7d32; font-size: 0.9rem;">
                        <strong> Your subscription is now active!</strong> You can now enjoy discounted services and priority booking.
                    </p>
                </div>
                <?php endif; ?>
                
                <div class="next-steps">
                    <h4>What happens next?</h4>
                    <ul>
                        <li>We'll process your order within 48 hours</li>
                        <li>You'll receive updates via phone/email</li>
                        <li>Your items will be ready for delivery on the scheduled date</li>
                        <li>Payment will be collected upon delivery (if cash selected)</li>
                    </ul>
                </div>
                
                <div class="action-buttons">
                    <a href="/allura/service.php" class="btn btn-primary">Continue Shopping</a>
                    <a href="/allura/home.php" class="btn btn-secondary">Go to Home</a>
                </div>
            </div>
        </div>
    </body>
    </html>
    <?php
    exit();
}

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

$me = User::getCurrentUser();
$items = getCartItems();
$cart_items = isset($_SESSION['cart_items']) ? $_SESSION['cart_items'] : [];

if (empty($items) && empty($cart_items)) {
    header("Location: /allura/cart.php");
    exit();
}

$required_fields = ['customer_name', 'customer_phone', 'customer_address', 'payment_method'];
$errors = [];

foreach ($required_fields as $field) {
    if (empty($_POST[$field])) {
        $errors[] = "Please fill in all required fields.";
        break;
    }
}

$valid_payment_methods = ['cash', 'card', 'online'];
if (!in_array($_POST['payment_method'], $valid_payment_methods)) {
    $errors[] = "Invalid payment method selected.";
}

if ($_POST['payment_method'] === 'card') {
    $card_fields = ['card_number', 'expiry_date', 'cvv', 'card_holder_name'];
    foreach ($card_fields as $field) {
        if (empty($_POST[$field])) {
            $errors[] = "Please fill in all card details.";
            break;
        }
    }
    
    $card_number = preg_replace('/\s/', '', $_POST['card_number']);
    if (strlen($card_number) < 13 || strlen($card_number) > 19) {
        $errors[] = "Invalid card number.";
    }
    
    if (!preg_match('/^\d{2}\/\d{2}$/', $_POST['expiry_date'])) {
        $errors[] = "Invalid expiry date format.";
    }
    
    if (strlen($_POST['cvv']) < 3 || strlen($_POST['cvv']) > 4) {
        $errors[] = "Invalid CVV.";
    }
    
} elseif ($_POST['payment_method'] === 'online') {
    if (empty($_POST['online_method'])) {
        $errors[] = "Please select an online payment method.";
    }
}

if (!empty($errors)) {
    $_SESSION['checkout_errors'] = $errors;
    $_SESSION['checkout_data'] = $_POST;
    header("Location: ../checkout.php");
    exit();
}

function calcDelDt($items, $db) {
    $max_delivery_days = 3;
    $has_express = false;
    
    foreach ($items as $item) {
        $service_id = isset($item['service_id']) ? $item['service_id'] : (isset($item['id']) ? $item['id'] : null);
        if (!$service_id) continue;
        
        $selected_options = isset($item['selected_options']) ? $item['selected_options'] : '{}';
        
        if (!empty($selected_options)) {
            if (is_string($selected_options)) {
                $options_array = json_decode($selected_options, true);
            } elseif (is_array($selected_options)) {
                $options_array = $selected_options;
            } else {
                $options_array = [];
            }
            
            if (isset($options_array['delivery_time'])) {
                $delivery_value = is_array($options_array['delivery_time']) ? 
                                (isset($options_array['delivery_time']['value']) ? $options_array['delivery_time']['value'] : $options_array['delivery_time']) : 
                                $options_array['delivery_time'];
                                
                if ($delivery_value === '24_hours' || $delivery_value === 'express') {
                    $has_express = true;
                }
            }
        }
    }
    
    if ($has_express) {
        $delivery_days = rand(0, 2);
    } else {
        $delivery_days = rand(3, 5);
    }
    
    $delivery_date = date('Y-m-d', strtotime("+{$delivery_days} days"));
    
    $day_of_week = date('N', strtotime($delivery_date));
    if ($day_of_week == 5) { 
        $delivery_date = date('Y-m-d', strtotime($delivery_date . ' +1 day'));
    }
    
    return $delivery_date;
}

try {
    $db = getDBConnection();
    $db->beginTransaction();
    
    $details = [];
    $subtotal = 0;
    
    if (!empty($items)) {
        $ph = str_repeat('?,', count($items) - 1) . '?';
        $sql = "SELECT id, name, price FROM services WHERE id IN ($ph)";
        
        $ids = array_column($items, 'service_id');
        $st = $db->prepare($sql);
        $st->execute($ids);
        $rows = $st->fetchAll(PDO::FETCH_ASSOC);
        
        $map = [];
        foreach ($rows as $svc) {
            $map[$svc['id']] = $svc;
        }
        
        foreach ($items as $it) {
            $sid = $it['service_id'];
            if (isset($map[$sid])) {
                $svc = $map[$sid];
                $base_price = $svc['price'];
                $options_price = 0;
                
                if (isset($it['selected_options']) && is_array($it['selected_options'])) {
                    foreach ($it['selected_options'] as $key => $opt) {
                        if ($key === 'addons' && is_array($opt)) {
                            foreach ($opt as $addon) {
                                if (isset($addon['price'])) {
                                    $options_price += floatval($addon['price']);
                                }
                            }
                        } elseif (is_array($opt)) {
                            if (isset($opt['price'])) {
                                $options_price += floatval($opt['price']);
                            } elseif (isset($opt['price_modifier'])) {
                                $options_price += floatval($opt['price_modifier']);
                            }
                        }
                    }
                }
                
                if (TieredPricing::isTieredService($sid)) {
                    $tiered_total = TieredPricing::calculateTotalWithTiers($sid, $it['quantity'], $base_price);
                    $tp = $tiered_total + $options_price;
                } else {
                    $tp = ($base_price + $options_price) * $it['quantity'];
                }
                $subtotal += $tp;
                
                $details[] = [
                    'service_id' => $sid,
                    'name' => $svc['name'],
                    'price' => $base_price,
                    'quantity' => $it['quantity'],
                    'total_price' => $tp,
                    'selected_options' => $it['selected_options'] ?? null,
                    'type' => 'regular'
                ];
            }
        }
    }
    
    if (!empty($cart_items)) {
        $service_ids = array_unique(array_column($cart_items, 'service_id'));
        if (!empty($service_ids)) {
            $ph = str_repeat('?,', count($service_ids) - 1) . '?';
            $sql = "SELECT id, name, price, category FROM services WHERE id IN ($ph)";
            
            $st = $db->prepare($sql);
            $st->execute($service_ids);
            $service_rows = $st->fetchAll(PDO::FETCH_ASSOC);
            
            $service_map = [];
            foreach ($service_rows as $svc) { 
                $service_map[$svc['id']] = $svc; 
            }
            
            foreach ($cart_items as $index => $item) {
                $sid = $item['service_id'];
                if (isset($service_map[$sid])) {
                    $svc = $service_map[$sid];
                    $base_price = $svc['price'];
                    $quantity = $item['quantity'];
                    $options_price = 0;
                    
                    if (is_string($item['selected_options'])) {
                        $selected_options = json_decode($item['selected_options'], true);
                    } elseif (is_array($item['selected_options'])) {
                        $selected_options = $item['selected_options'];
                    } else {
                        $selected_options = [];
                    }
                    
                    if ($selected_options) {
                        foreach ($selected_options as $option_type => $option_data) {
                            if ($option_type === 'addons' && is_array($option_data)) {
                                foreach ($option_data as $addon) {
                                    if (isset($addon['price'])) {
                                        $options_price += floatval($addon['price']);
                                    }
                                }
                            } elseif (is_array($option_data)) {
                                if (isset($option_data['price'])) {
                                    $options_price += floatval($option_data['price']);
                                } elseif (isset($option_data['price_modifier'])) {
                                    $options_price += floatval($option_data['price_modifier']);
                                }
                            }
                        }
                    }
                    
                    if (TieredPricing::isTieredService($sid)) {
                        $tiered_total = TieredPricing::calculateTotalWithTiers($sid, $quantity, $base_price);
                        $total_price = $tiered_total + $options_price;
                    } else {
                        $total_price = ($base_price + $options_price) * $quantity;
                    }
                    
                    $subtotal += $total_price;
                    
                    $details[] = [
                        'service_id' => $sid,
                        'name' => $svc['name'],
                        'price' => $base_price,
                        'quantity' => $quantity,
                        'total_price' => $total_price,
                        'selected_options' => $item['selected_options'],
                        'type' => 'custom'
                    ];
                }
            }
        }
    }
    
     if (empty($details)) {
         throw new Exception("No valid items found in cart.");
     }
     
     $discount_amount = 0;
     $offer_title = '';
     $offer_id = null;
     
     if ($subtotal > 0) {
         try {
             $stmt = $db->prepare("
                 SELECT u.*, 
                        COUNT(o.id) as order_count,
                        CASE 
                            WHEN EXISTS(SELECT 1 FROM subscriptions s WHERE s.user_id = u.id AND s.status = 'active') THEN 'subscribed'
                            WHEN COUNT(o.id) >= 5 THEN 'regular'
                            WHEN COUNT(o.id) > 0 THEN 'normal'
                            ELSE 'new'
                        END as customer_type
                 FROM users u 
                 LEFT JOIN orders o ON u.id = o.user_id 
                 WHERE u.id = ?
                 GROUP BY u.id
             ");
             $stmt->execute([$me['id']]);
             $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
             $customer_type = $user_data['customer_type'] ?? 'new';
             
             $stmt = $db->prepare("
                 SELECT * FROM offers 
                 WHERE status = 'active' 
                 AND start_date <= CURDATE() 
                 AND end_date >= CURDATE()
                 AND (target_customers = 'all' OR target_customers = ?)
                 AND min_order_amount <= ?
                 AND (usage_limit IS NULL OR used_count < usage_limit)
                 ORDER BY discount_value DESC
                 LIMIT 1
             ");
             $stmt->execute([$customer_type, $subtotal]);
             $offer = $stmt->fetch(PDO::FETCH_ASSOC);
             
             if ($offer) {
                 if ($offer['discount_type'] === 'percentage') {
                     $discount_amount = ($subtotal * $offer['discount_value']) / 100;
                     if ($offer['max_discount_amount'] && $discount_amount > $offer['max_discount_amount']) {
                         $discount_amount = $offer['max_discount_amount'];
                     }
                 } else {
                     $discount_amount = $offer['discount_value'];
                 }
                 $discount_amount = min($discount_amount, $subtotal);
                 $offer_title = $offer['title'];
                 $offer_id = $offer['id'];
             }
         } catch (PDOException $e) {
             error_log("Error applying discount in checkout: " . $e->getMessage());
         }
     }
     
     $discounted_total = $subtotal - $discount_amount;
     
     $tax = $discounted_total * 0.08; 
     $total_amount = $discounted_total + $tax;
    
    $customer_name = trim($_POST['customer_name']);
    $customer_phone = trim($_POST['customer_phone']);
    $customer_address = trim($_POST['customer_address']);
    
    $useSub = isset($_POST['use_subscription']) && $_POST['use_subscription'] == '1';
    $subUsed = false;
    
    if ($useSub) {
        $stmt = $db->prepare("
            SELECT * FROM subscriptions 
            WHERE user_id = ? AND status = 'active' AND end_date >= CURDATE() AND usage_count < max_usage
            ORDER BY created_at DESC LIMIT 1
        ");
        $stmt->execute([$me['id']]);
        $subInfo = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($subInfo) {
            $delivery_date = date('Y-m-d', strtotime('+1 day'));
            $subUsed = true;
        } else {
            $all_items = array_merge($items, $cart_items);
            $delivery_date = calcDelDt($all_items, $db);
        }
    } else {
        $all_items = array_merge($items, $cart_items);
        $delivery_date = calcDelDt($all_items, $db);
    }
    
    $delivery_time = !empty($_POST['delivery_time']) ? $_POST['delivery_time'] : null;
    $payment_method = $_POST['payment_method'];
    $notes = !empty($_POST['notes']) ? trim($_POST['notes']) : null;
    
    $order_sql = "INSERT INTO orders (user_id, customer_name, customer_phone, customer_address, 
                  total_amount, status, payment_method, delivery_date, delivery_time, notes) 
                  VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?)";
    
    $order_stmt = $db->prepare($order_sql);
    $order_stmt->execute([
        $me['id'],
        $customer_name,
        $customer_phone,
        $customer_address,
        $total_amount,
        $payment_method,
        $delivery_date,
        $delivery_time,
        $notes
    ]);
    
    $order_id = $db->lastInsertId();
    
    $item_sql = "INSERT INTO order_items (order_id, service_id, quantity, price, selected_options, weight_kg, pieces_count) VALUES (?, ?, ?, ?, ?, ?, ?)";
    $item_stmt = $db->prepare($item_sql);
    
    foreach ($details as $item) {
        $selected_options = null;
        if (isset($item['selected_options']) && $item['selected_options']) {
            if (is_array($item['selected_options'])) {
                $selected_options = json_encode($item['selected_options']);
            } elseif (is_string($item['selected_options'])) {
                $selected_options = $item['selected_options'];
            }
        }
        
        $weight_kg = null;
        $pieces_count = null;
        
        if (isset($item['type']) && $item['type'] === 'custom') {
            $service_stmt = $db->prepare("SELECT category FROM services WHERE id = ?");
            $service_stmt->execute([$item['service_id']]);
            $service_data = $service_stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($service_data) {
                if ($service_data['category'] === 'washing') {
                    $weight_kg = $item['quantity'];
                } elseif ($service_data['category'] === 'ironing') {
                    $pieces_count = $item['quantity'];
                }
            }
        }
        
        $item_stmt->execute([
            $order_id,
            $item['service_id'],
            $item['quantity'],
            $item['price'],
            $selected_options,
            $weight_kg,
            $pieces_count
        ]);
        
        $service_check_stmt = $db->prepare("SELECT category FROM services WHERE id = ?");
        $service_check_stmt->execute([$item['service_id']]);
        $service_info = $service_check_stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($service_info && $service_info['category'] === 'subscription') {
            $subType = 'monthly'; 
            $planName = 'Monthly Subscription';
            $durDays = 30;
            $maxUse = 10;
            
            if ($selected_options) {
                if (is_string($selected_options)) {
                    $options_array = json_decode($selected_options, true);
                } elseif (is_array($selected_options)) {
                    $options_array = $selected_options;
                } else {
                    $options_array = [];
                }
                if (isset($options_array['subscription_type'])) {
                    $subscription_value = is_array($options_array['subscription_type']) ? 
                                        (isset($options_array['subscription_type']['value']) ? $options_array['subscription_type']['value'] : $options_array['subscription_type']) : 
                                        $options_array['subscription_type'];
                                        
                    if ($subscription_value === 'weekly') {
                        $subType = 'weekly';
                        $planName = 'Weekly Subscription';
                        $durDays = 7;
                        $maxUse = 3;
                    }
                }
            }
            
            $start_date = $delivery_date;
            $end_date = date('Y-m-d', strtotime($start_date . " +{$durDays} days"));
            
            $sub_sql = "INSERT INTO subscriptions (user_id, plan_name, plan_type, price, start_date, end_date, status, usage_count, max_usage) VALUES (?, ?, ?, ?, ?, ?, 'active', 0, ?)";
            $sub_stmt = $db->prepare($sub_sql);
            $sub_stmt->execute([
                $me['id'],
                $planName,
                $subType,
                $item['total_price'],
                $start_date,
                $end_date,
                $maxUse
            ]);
            
            if (!isset($_SESSION['subscription_created'])) {
                $_SESSION['subscription_created'] = [];
            }
            $_SESSION['subscription_created'][] = [
                'plan_name' => $planName,
                'plan_type' => $subType,
                'start_date' => $start_date,
                'end_date' => $end_date,
                'max_usage' => $maxUse
            ];
        }
    }
    
    if ($offer_id && $discount_amount > 0) {
        $usage_sql = "INSERT INTO offer_usage (offer_id, user_id, order_id, discount_amount, used_at) VALUES (?, ?, ?, ?, NOW())";
        $usage_stmt = $db->prepare($usage_sql);
        $usage_stmt->execute([$offer_id, $me['id'], $order_id, $discount_amount]);
        
        $update_offer_sql = "UPDATE offers SET used_count = used_count + 1 WHERE id = ?";
        $update_offer_stmt = $db->prepare($update_offer_sql);
        $update_offer_stmt->execute([$offer_id]);
    }
    
    if ($subUsed && isset($subInfo)) {
        $upd_sql = "UPDATE subscriptions SET usage_count = usage_count + 1 WHERE id = ?";
        $upd_stmt = $db->prepare($upd_sql);
        $upd_stmt->execute([$subInfo['id']]);
    }
    
    clearCart();
    unset($_SESSION['cart_items']);
    
    $db->commit();
    
    $_SESSION['order_success'] = [
        'order_id' => $order_id,
        'subtotal' => $subtotal,
        'discount_amount' => $discount_amount,
        'discount_title' => $offer_title,
        'tax_amount' => $tax,
        'total_amount' => $total_amount,
        'delivery_date' => $delivery_date,
        'payment_method' => $payment_method
    ];
    
    header("Location: /allura/php/process_checkout.php?success=1");
    exit();
    
} catch (Exception $e) {
    if ($db->inTransaction()) {
        $db->rollback();
    }
    
    error_log("Checkout error: " . $e->getMessage() . " in " . $e->getFile() . " on line " . $e->getLine());
    
    $_SESSION['checkout_errors'] = ["Error: " . $e->getMessage() . " (Line: " . $e->getLine() . ")"];
    $_SESSION['checkout_data'] = $_POST;
    header("Location: /allura/checkout.php");
    exit();
}
?>
