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

header('Content-Type: application/json');

function getBestOffer($uid, $amt) {
    $db = getDBConnection();
    $u = $db->prepare("SELECT u.*, COUNT(o.id) as oc FROM users u LEFT JOIN orders o ON u.id = o.user_id WHERE u.id = ? GROUP BY u.id");
    $u->execute([$uid]);
    $user = $u->fetch();
    if (!$user) return ['offer_id' => null, 'offer_title' => null, 'discount_amount' => 0];
    
    $type = 'new';
    if ($user['oc'] >= 5) $type = 'regular';
    else if ($user['oc'] > 0) $type = 'normal';
    
    $o = $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 <= ? ORDER BY discount_value DESC LIMIT 1");
    $o->execute([$type, $amt]);
    $offer = $o->fetch();
    if (!$offer) return ['offer_id' => null, 'offer_title' => null, 'discount_amount' => 0];
    
    $disc = $offer['discount_type'] === 'percentage' ? ($amt * $offer['discount_value']) / 100 : $offer['discount_value'];
    if ($offer['max_discount_amount'] && $disc > $offer['max_discount_amount']) $disc = $offer['max_discount_amount'];
    $disc = min($disc, $amt);
    
    return ['offer_id' => $offer['id'], 'offer_title' => $offer['title'], 'discount_amount' => $disc];
}

if (!User::isLoggedIn()) {
    echo json_encode(array('success' => false, 'message' => 'Please login to use cart functions'));
    exit();
}

$action = isset($_POST['action']) ? $_POST['action'] : (isset($_GET['action']) ? $_GET['action'] : '');

switch ($action) {
    case 'add':
    if (!isset($_POST['service_id']) || empty($_POST['service_id'])) {
        echo json_encode(array('success' => false, 'message' => 'Service ID is required'));
        exit();
    }

    $service_id = intval($_POST['service_id']);
    $qty = isset($_POST['quantity']) ? intval($_POST['quantity']) : 1; 

    $count = addToCart($service_id, $qty);
    
    echo json_encode(array(
        'success' => true, 
        'message' => 'Service added to cart successfully',
        'cart_count' => $count
    ));
    break;

    case 'add_service':
    if (!isset($_POST['service_id']) || empty($_POST['service_id'])) {
        echo json_encode(['success' => false, 'message' => 'Service ID is required']);
        exit();
    }

    $service_id = intval($_POST['service_id']);
    $qty = isset($_POST['quantity']) ? intval($_POST['quantity']) : 1;
    $selected_options = isset($_POST['selected_options']) ? $_POST['selected_options'] : null;
    $special_instructions = isset($_POST['special_instructions']) ? $_POST['special_instructions'] : null;

            // 🟩 new fields for pickup option and address
    $pickup_option = isset($_POST['pickup_option']) ? trim($_POST['pickup_option']) : null;
    $pickup_address = isset($_POST['pickup_address']) ? trim($_POST['pickup_address']) : null;

    try {
        if ($selected_options && is_string($selected_options)) {
            $selected_options = json_decode($selected_options, true);
        }

                // 🟩 pass new fields into addToCart()
        addToCart($service_id, $qty, $selected_options, $special_instructions, $pickup_option, $pickup_address);
        $count = getCartCount();

        echo json_encode([
            'success' => true, 
            'message' => 'Service added to cart successfully',
            'cart_count' => $count
        ]);
    } catch (Exception $e) {
        echo json_encode([
            'success' => false, 
            'message' => 'An error occurred while adding to cart: ' . $e->getMessage()
        ]);
    }
    break;


    case 'remove':
    if (!isset($_POST['service_id']) || empty($_POST['service_id'])) {
        echo json_encode(['success' => false, 'message' => 'Service ID is required']);
        exit();
    }

    $service_id = intval($_POST['service_id']);

    try {
        removeFromCart($service_id);
        
        echo json_encode([
            'success' => true, 
            'message' => 'Service removed from cart successfully'
        ]);
    } catch (Exception $e) {
        echo json_encode([
            'success' => false, 
            'message' => 'An error occurred while removing item from cart: ' . $e->getMessage()
        ]);
    }
    break;

    case 'update':
    if (!isset($_POST['service_id']) || !isset($_POST['change'])) {
        echo json_encode(['success' => false, 'message' => 'Service ID and change are required']);
        exit();
    }

    $service_id = intval($_POST['service_id']);
    $chg = intval($_POST['change']);

    try {
        $items = getCartItems();
        $found = false;

        foreach ($items as &$it) {
            if ($it['service_id'] == $service_id) {
                $new_quantity = $it['quantity'] + $chg;
                if ($new_quantity < 1) {
                    $new_quantity = 1;
                }
                updateCartItemQuantity($service_id, $new_quantity);
                $found = true;
                break;
            }
        }

        if (!$found) {
            echo json_encode([
                'success' => false,
                'message' => 'Item not found in cart'
            ]);
            exit();
        }

        echo json_encode([
            'success' => true,
            'message' => 'Cart updated successfully'
        ]);
    } catch (Exception $e) {
        error_log("Error in cart_handler.php: " . $e->getMessage());
        echo json_encode([
            'success' => false,
            'message' => 'An error occurred while updating cart'
        ]);
    }
    break;

    case 'update_cart':
    if (!isset($_POST['service_id']) || !isset($_POST['quantity'])) {
        echo json_encode(['success' => false, 'message' => 'Service ID and quantity are required']);
        exit();
    }

    $service_id = intval($_POST['service_id']);
    $quantity = intval($_POST['quantity']);

    try {
        if ($quantity <= 0) {
            removeFromCart($service_id);
        } else {
            updateCartItemQuantity($service_id, $quantity);
        }

        echo json_encode([
            'success' => true,
            'message' => 'Cart updated successfully'
        ]);
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => 'An error occurred while updating cart: ' . $e->getMessage()
        ]);
    }
    break;

    case 'update_cart':
    if (!isset($_POST['cart_index']) || !isset($_POST['change'])) {
        echo json_encode(['success' => false, 'message' => 'Cart index and change are required']);
        exit();
    }

    $cart_index = intval($_POST['cart_index']);
    $change = intval($_POST['change']);

    try {
        safe_session_start();
        $cart_items = isset($_SESSION['cart_items']) ? $_SESSION['cart_items'] : [];

        if (!isset($cart_items[$cart_index])) {
            echo json_encode(['success' => false, 'message' => 'Cart item not found']);
            exit();
        }

        $new_quantity = $cart_items[$cart_index]['quantity'] + $change;
        if ($new_quantity < 1) {
            $new_quantity = 1;
        }

        $cart_items[$cart_index]['quantity'] = $new_quantity;
        $_SESSION['cart_items'] = $cart_items;

        echo json_encode(['success' => true, 'message' => 'Cart updated successfully']);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Error updating cart: ' . $e->getMessage()]);
    }
    break;

    case 'remove_cart_item':
    if (!isset($_POST['cart_index'])) {
        echo json_encode(['success' => false, 'message' => 'Cart index is required']);
        exit();
    }

    $cart_index = intval($_POST['cart_index']);

    try {
        safe_session_start();
        $cart_items = isset($_SESSION['cart_items']) ? $_SESSION['cart_items'] : [];

        if (isset($cart_items[$cart_index])) {
            unset($cart_items[$cart_index]);
            $_SESSION['cart_items'] = array_values($cart_items);
        }

        echo json_encode(['success' => true, 'message' => 'Item removed successfully']);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Error removing item: ' . $e->getMessage()]);
    }
    break;

    case 'remove_cart_item_old':
    if (!isset($_POST['service_id'])) {
        echo json_encode(['success' => false, 'message' => 'Service ID is required']);
        exit();
    }

    $service_id = intval($_POST['service_id']);

    try {
        removeFromCart($service_id);

        echo json_encode([
            'success' => true,
            'message' => 'Item removed from cart successfully'
        ]);
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => 'An error occurred while removing item: ' . $e->getMessage()
        ]);
    }
    break;

    case 'get_details':
    default:
    try {
        $usr = User::getCurrentUser();
        $items = getCartItems();
        
        $details = [];
        $tot = 0;
        
        if (!empty($items)) {
            $db = getDBConnection();
            
            $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];
                    
                    $item_price = $svc['price'];
                    
                    $options_price = 0;
                    $options_text = '';
                    if (isset($it['selected_options']) && is_array($it['selected_options'])) {
                        $options_array = [];
                        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']);
                                    }
                                    $options_array[] = $addon['name'] ?? 'Add-on';
                                }
                            } elseif (is_array($opt) && isset($opt['name'])) {
                                if (isset($opt['price'])) {
                                    $options_price += floatval($opt['price']);
                                }
                                $display = ucfirst(str_replace('_', ' ', $key)) . ': ' . $opt['name'];
                                if (isset($opt['price']) && $opt['price'] > 0) {
                                    $display .= ' (+SAR ' . number_format($opt['price'], 2) . ')';
                                }
                                $options_array[] = $display;
                            }
                        }
                        $options_text = implode(', ', $options_array);
                    }
                    
                    if (TieredPricing::isTieredService($sid)) {
                        $tiered_total = TieredPricing::calculateTotalWithTiers($sid, $it['quantity'], $item_price);
                        $total_item_price = $tiered_total + $options_price;
                    } else {
                        $total_item_price = ($item_price + $options_price) * $it['quantity'];
                    }
                    $tot += $total_item_price;
                    
                    $tier_info = TieredPricing::getTierInfo($sid, $it['quantity']);
                    
                    $details[] = [
                        'service_id' => $sid,
                        'name' => $svc['name'],
                        'price' => $svc['price'],
                        'options_price' => $options_price,
                        'quantity' => $it['quantity'],
                        'total_price' => $total_item_price,
                        'selected_options' => $it['selected_options'] ?? null,
                        'options_text' => $options_text,
                        'tier_info' => $tier_info,
                        'is_tiered' => TieredPricing::isTieredService($sid),
                        'image' => $svc['image'] ?? null,
                            // new pickup fields
                        'pickup_option' => isset($it['pickup_option']) ? $it['pickup_option'] : null,
                        'pickup_address' => isset($it['pickup_address']) ? $it['pickup_address'] : null
                    ];
                }
            }
        }
        
        
        $discount_amount = 0;
        $offer_title = '';
        $offer_id = null;
        
        if ($tot > 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([$usr['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, $tot]);
                $offer = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($offer) {
                    if ($offer['discount_type'] === 'percentage') {
                        $discount_amount = ($tot * $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, $tot);
                    $offer_title = $offer['title'];
                    $offer_id = $offer['id'];
                }
            } catch (PDOException $e) {
                error_log("Error applying discount: " . $e->getMessage());
            }
        }
        
        $discounted_total = $tot - $discount_amount;
        $tax = $discounted_total * 0.08;
        $grand = $discounted_total + $tax;

        echo json_encode([
            'success' => true,
            'cartDetails' => $details,
            'totalAmount' => $tot,
            'discountAmount' => $discount_amount,
            'discountTitle' => $offer_title,
            'discountedTotal' => $discounted_total,
            'taxAmount' => $tax,
            'grandTotal' => $grand,
            'userName' => $usr['name'],
            'customerType' => $customer_type,
            'offer' => [
                'id' => $offer_id,
                'title' => $offer_title,
                'discount_amount' => $discount_amount
            ]
        ]);
    } catch (Exception $e) {
        error_log("Error in cart_handler.php: " . $e->getMessage());
        echo json_encode([
            'success' => false,
            'message' => 'An error occurred while fetching cart details: ' . $e->getMessage()
        ]);
    }
    break;
}

?>