<?php
session_start();
header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 0);

// Catch all errors and output as JSON
set_error_handler(function($errno, $errstr, $errfile, $errline) {
    error_log("Error [$errno]: $errstr in $errfile:$errline");
    http_response_code(500);
    $response = [
        'success' => false,
        'message' => 'Error: ' . $errstr . ' in ' . basename($errfile) . ' on line ' . $errline
    ];
    // Check if response has started
    if (!headers_sent()) {
        header('Content-Type: application/json');
        echo json_encode($response);
    }
    exit;
});

// Catch fatal errors
register_shutdown_function(function() {
    $error = error_get_last();
    if ($error !== NULL) {
        error_log("Fatal Error: " . print_r($error, true));
        http_response_code(500);
        $response = [
            'success' => false,
            'message' => 'Fatal Error: ' . $error['message'] . ' in ' . basename($error['file']) . ' on line ' . $error['line']
        ];
        if (!headers_sent()) {
            header('Content-Type: application/json');
            echo json_encode($response);
        }
    }
});

require_once __DIR__ . '/config/db.php';


if ($conn->connect_error) {
    http_response_code(500);
    die(json_encode(['success' => false, 'message' => 'Database connection failed: ' . $conn->connect_error]));
}

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'User not authenticated']);
    exit;
}

$user_id = $_SESSION['user_id'];
$action = $_GET['action'] ?? '';

// Handle different actions
switch ($action) {
    case 'place_order':
        placeOrder();
        break;
    case 'get_order_summary':
        getOrderSummary();
        break;
    case 'validate_address':
        validateAddress();
        break;
    case 'apply_coupon':
        applyCoupon();
        break;
    default:
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
}

// Place order
function placeOrder() {
    global $conn, $user_id;

    try {
        $raw_input = file_get_contents('php://input');
        $data = json_decode($raw_input, true);
        
        if (!$data) {
            throw new Exception("Invalid JSON received");
        }

        // Set default values for optional fields
        $data['company'] = $data['company'] ?? '';
        $data['order_notes'] = $data['order_notes'] ?? '';

        // Validate required fields
        $required = ['first_name', 'last_name', 'email', 'phone', 'country', 'address', 'city', 'postcode', 'payment_method'];
        foreach ($required as $field) {
            if (empty($data[$field])) {
                throw new Exception("Missing required field: $field");
            }
        }

        // Get cart items
        $cart_query = $conn->prepare("SELECT * FROM cart WHERE user_id = ?");
        if (!$cart_query) {
            throw new Exception("Cart query prepare failed: " . $conn->error);
        }
        $cart_query->bind_param("i", $user_id);
        $cart_query->execute();
        $cart_result = $cart_query->get_result();

        if ($cart_result->num_rows === 0) {
            throw new Exception("Cart is empty");
        }

        // Calculate totals
        $subtotal = 0;
        $items = [];
        while ($item = $cart_result->fetch_assoc()) {
            $item_total = $item['price'] * $item['quantity'];
            $subtotal += $item_total;
            $items[] = $item;
        }

        $shipping = 500;
        $tax = round($subtotal * 0.1, 2);
        $total = $subtotal + $shipping + $tax;

        // Prepare shipping info
        $ship_different = $data['ship_to_different'] ?? false;
        $shipping_country = $ship_different ? ($data['shipping_country'] ?? $data['country']) : $data['country'];
        $shipping_address = $ship_different ? ($data['shipping_address'] ?? $data['address']) : $data['address'];
        $shipping_city = $ship_different ? ($data['shipping_city'] ?? $data['city']) : $data['city'];
        $shipping_postcode = $ship_different ? ($data['shipping_postcode'] ?? $data['postcode']) : $data['postcode'];
        // If payment_intent_id supplied from client after successful Stripe confirmation,
        // mark order as paid. (For production, verify payment server-side with Stripe API.)
        $status = 'pending';
        if (!empty($data['payment_intent_id'])) {
            $status = 'paid';
        }

        // Create order - using simple INSERT with all values
        $insert_sql = "INSERT INTO orders (
            user_id, first_name, last_name, email, phone,
            billing_country, billing_address, billing_city, billing_postcode,
            shipping_country, shipping_address, shipping_city, shipping_postcode,
            company, order_notes, payment_method, subtotal, tax, shipping, total, status
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        $stmt = $conn->prepare($insert_sql);
        if (!$stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }

        $bind_result = $stmt->bind_param(
            "isssssssssssssssdddds",
            $user_id,
            $data['first_name'],
            $data['last_name'],
            $data['email'],
            $data['phone'],
            $data['country'],
            $data['address'],
            $data['city'],
            $data['postcode'],
            $shipping_country,
            $shipping_address,
            $shipping_city,
            $shipping_postcode,
            $data['company'],
            $data['order_notes'],
            $data['payment_method'],
            $subtotal,
            $tax,
            $shipping,
            $total,
            $status
        );
        
        if (!$bind_result) {
            throw new Exception("Bind failed: " . $stmt->error);
        }

        if (!$stmt->execute()) {
            throw new Exception("Execute failed: " . $stmt->error);
        }

        $order_id = $conn->insert_id;

        // Add order items
        foreach ($items as $item) {
            $item_total = $item['price'] * $item['quantity'];
            
            $item_stmt = $conn->prepare(
                "INSERT INTO order_items (order_id, product_id, product_name, price, quantity, total)
                 VALUES (?, ?, ?, ?, ?, ?)"
            );
            
            if (!$item_stmt) {
                throw new Exception("Item prepare failed: " . $conn->error);
            }

            if (!$item_stmt->bind_param(
                "isidii",
                $order_id,
                $item['product_id'],
                $item['product_name'],
                $item['price'],
                $item['quantity'],
                $item_total
            )) {
                throw new Exception("Item bind failed: " . $item_stmt->error);
            }
            
            if (!$item_stmt->execute()) {
                throw new Exception("Item execute failed: " . $item_stmt->error);
            }
            
            $item_stmt->close();
        }

        // Clear cart
        $delete_stmt = $conn->prepare("DELETE FROM cart WHERE user_id = ?");
        if (!$delete_stmt) {
            throw new Exception("Delete prepare failed: " . $conn->error);
        }
        $delete_stmt->bind_param("i", $user_id);
        if (!$delete_stmt->execute()) {
            throw new Exception("Delete execute failed: " . $delete_stmt->error);
        }
        $delete_stmt->close();

        // Return success
        echo json_encode([
            'success' => true,
            'message' => 'Order placed successfully',
            'order_id' => $order_id,
            'total' => $total
        ]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => 'Order placement failed: ' . $e->getMessage()
        ]);
    }
}

// Get order summary
function getOrderSummary() {
    global $conn, $user_id;

    $query = $conn->prepare("
        SELECT id, product_id, product_name, price, quantity, (price * quantity) as total
        FROM cart
        WHERE user_id = ?
    ");
    $query->bind_param("i", $user_id);
    $query->execute();
    $result = $query->get_result();

    $items = [];
    $subtotal = 0;
    while ($row = $result->fetch_assoc()) {
        $items[] = $row;
        $subtotal += $row['total'];
    }

    $shipping = 500;
    $tax = round($subtotal * 0.1, 2);
    $total = $subtotal + $shipping + $tax;

    echo json_encode([
        'success' => true,
        'items' => $items,
        'subtotal' => $subtotal,
        'shipping' => $shipping,
        'tax' => $tax,
        'total' => $total
    ]);
}

// Validate address
function validateAddress() {
    global $conn;

    $data = json_decode(file_get_contents('php://input'), true);

    $errors = [];
    if (empty($data['email']) || !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Invalid email address';
    }
    if (empty($data['phone']) || strlen($data['phone']) < 10) {
        $errors[] = 'Invalid phone number';
    }
    if (empty($data['postcode'])) {
        $errors[] = 'Postcode is required';
    }
    if (empty($data['address'])) {
        $errors[] = 'Address is required';
    }
    if (empty($data['city'])) {
        $errors[] = 'City is required';
    }

    if (!empty($errors)) {
        echo json_encode(['success' => false, 'errors' => $errors]);
    } else {
        echo json_encode(['success' => true, 'message' => 'Address is valid']);
    }
}

// Apply coupon
function applyCoupon() {
    global $conn;

    $data = json_decode(file_get_contents('php://input'), true);
    $coupon_code = $data['coupon_code'] ?? '';

    if (empty($coupon_code)) {
        echo json_encode(['success' => false, 'message' => 'Coupon code is required']);
        exit;
    }

    // Check coupon validity
    $coupon_query = $conn->prepare("
        SELECT * FROM coupons
        WHERE code = ? AND is_active = 1 AND expires_at > NOW()
    ");
    $coupon_query->bind_param("s", $coupon_code);
    $coupon_query->execute();
    $coupon_result = $coupon_query->get_result();

    if ($coupon_result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid or expired coupon']);
        exit;
    }

    $coupon = $coupon_result->fetch_assoc();

    echo json_encode([
        'success' => true,
        'message' => 'Coupon applied successfully',
        'discount_type' => $coupon['discount_type'],
        'discount_value' => $coupon['discount_value']
    ]);
}
?>
