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

$action = $_GET['action'] ?? 'list';
$user = requireAuth(['client', 'seller', 'admin']);

// 1. GET: Orders List
if ($action === 'list' && $_SERVER['REQUEST_METHOD'] === 'GET') {
    $sql = "SELECT o.* FROM orders o";
    $params = [];

    if ($user['role'] === 'seller') {
        $sql .= " WHERE EXISTS (SELECT 1 FROM order_items oi WHERE oi.order_id = o.id AND oi.seller_id = :sid)";
        $params['sid'] = $user['id'];
    } elseif ($user['role'] === 'client') {
        $sql .= " WHERE o.customer_id = :cid";
        $params['cid'] = $user['id'];
    }
    $sql .= " ORDER BY o.created_at DESC";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $orders = $stmt->fetchAll();

    if (!empty($orders)) {
        $orderIds = array_column($orders, 'id');
        $inClause = implode(',', array_fill(0, count($orderIds), '?'));

        $itemStmt = $pdo->prepare("SELECT id, order_id, product_id, variant_id, seller_id, product_name, variant_name, price, quantity, total FROM order_items WHERE order_id IN ($inClause)");
        $itemStmt->execute($orderIds);
        $allItems = $itemStmt->fetchAll();

        $itemsByOrder = [];
        foreach ($allItems as $item) {
            $itemsByOrder[$item['order_id']][] = $item;
        }

        foreach ($orders as &$ord) {
            $ord['items'] = $itemsByOrder[$ord['id']] ?? [];
            $ord['tracking_numbers'] = json_decode($ord['tracking_numbers'] ?? '{}', true) ?: (object)[];
        }
    }

    sendResponse(true, ['data' => $orders]);
}

// 2. POST: Create Order (Checkout)
if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $pdo->beginTransaction();
    try {
        $orderId = "ORD-" . date("Ymd") . "-" . rand(1000, 9999);
        $name = $_POST['customer_name'] ?? $user['name'];
        $phone = $_POST['customer_phone'] ?? '';
        $address = $_POST['shipping_address'] ?? '';
        $paymentMethod = $_POST['payment_method'] ?? 'PromptPay';
        $subtotal = (float)($_POST['subtotal'] ?? 0);
        $discount = (float)($_POST['discount'] ?? 0);
        $total = (float)($_POST['total'] ?? 0);
        $couponCode = $_POST['coupon_code'] ?? null;
        $items = json_decode($_POST['items'] ?? '[]', true);

        if (empty($items)) {
            sendResponse(false, 'ไม่มีสินค้าในคำสั่งซื้อ', 400);
        }

        // Upload Slip File
        $slipPath = null;
        if (!empty($_FILES['slip']['name']) && $_FILES['slip']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = __DIR__ . '/../uploads/slips/';
            if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
            $ext = strtolower(pathinfo($_FILES['slip']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg', 'jpeg', 'png', 'webp', 'pdf'])) {
                $filename = "slip_{$orderId}_" . uniqid() . ".{$ext}";
                if (move_uploaded_file($_FILES['slip']['tmp_name'], $uploadDir . $filename)) {
                    $slipPath = 'uploads/slips/' . $filename;
                }
            }
        }

        $stmt = $pdo->prepare("INSERT INTO orders (id, customer_id, customer_name, customer_phone, shipping_address, subtotal, discount, coupon_code, total, payment_method, slip_image, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$orderId, $user['id'], $name, $phone, $address, $subtotal, $discount, $couponCode, $total, $paymentMethod, $slipPath, 'Pending']);

        $itemStmt = $pdo->prepare("INSERT INTO order_items (order_id, product_id, variant_id, seller_id, product_name, variant_name, price, quantity, total) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        foreach ($items as $item) {
            $itemStmt->execute([
                $orderId,
                $item['productId'] ?? $item['id'],
                $item['variantId'] ?? null,
                $item['sellerId'] ?? 1,
                $item['name'] ?? 'Product',
                $item['variantName'] ?? null,
                $item['price'] ?? 0,
                $item['quantity'] ?? 1,
                ($item['price'] ?? 0) * ($item['quantity'] ?? 1)
            ]);

            // Deduct stock
            if (!empty($item['variantId'])) {
                $pdo->prepare("UPDATE product_variants SET stock = GREATEST(0, stock - ?) WHERE id = ?")->execute([$item['quantity'] ?? 1, $item['variantId']]);
            } elseif (!empty($item['productId'])) {
                $pdo->prepare("UPDATE products SET stock = GREATEST(0, stock - ?) WHERE id = ?")->execute([$item['quantity'] ?? 1, $item['productId']]);
            }
        }

        $pdo->commit();
        sendResponse(true, ['message' => 'สั่งซื้อสินค้าสำเร็จ', 'order_id' => $orderId]);
    } catch (Exception $e) {
        $pdo->rollBack();
        sendResponse(false, $e->getMessage(), 500);
    }
}

// 3. POST: Verify Slip (Admin Only)
if ($action === 'verify_slip' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    requireAuth(['admin']);
    $body = getJsonInput();
    $orderId = $body['order_id'] ?? '';
    $status = $body['status'] ?? ''; // 'Paid' or 'Failed'
    $rejectReason = $body['reject_reason'] ?? null;

    if (!$orderId || !in_array($status, ['Paid', 'Failed'])) {
        sendResponse(false, 'ข้อมูลไม่ถูกต้อง', 400);
    }

    $sql = "UPDATE orders SET status = :status, reject_reason = :reject_reason, cancel_reason = :cancel_reason WHERE id = :id";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        'status' => $status,
        'reject_reason' => $status === 'Failed' ? $rejectReason : null,
        'cancel_reason' => $status === 'Failed' ? "ปฏิเสธสลิป: {$rejectReason}" : null,
        'id' => $orderId
    ]);

    sendResponse(true, "อัปเดตสถานะออเดอร์ {$orderId} เป็น {$status} เรียบร้อย");
}

// 4. POST: Update Tracking Number (Admin/Seller)
if ($action === 'update_tracking' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    requireAuth(['admin', 'seller']);
    $body = getJsonInput();
    $orderId = $body['order_id'] ?? '';
    $sellerKey = (string)($body['seller_id'] ?? $user['id']);
    $trackingNo = trim($body['tracking_number'] ?? '');

    $stmt = $pdo->prepare("SELECT tracking_numbers FROM orders WHERE id = ?");
    $stmt->execute([$orderId]);
    $order = $stmt->fetch();
    if (!$order) sendResponse(false, 'ไม่พบออเดอร์', 404);

    $trackingObj = json_decode($order['tracking_numbers'] ?? '{}', true) ?: [];
    $trackingObj[$sellerKey] = $trackingNo;

    $updateStmt = $pdo->prepare("UPDATE orders SET tracking_numbers = :tracking, status = 'Shipped' WHERE id = :id");
    $updateStmt->execute([
        'tracking' => json_encode($trackingObj),
        'id' => $orderId
    ]);

    sendResponse(true, 'บันทึกเลขพัสดุเรียบร้อย');
}
