<?php
// === ERROR REPORTING & HEADERS ===
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Cross-Origin Resource Sharing (CORS) aur Database configuration ko include karna
require_once '../config/cors.php';
require_once '../config/database.php';

// === DATABASE CONNECTION ===
$database = new Database();
$db = $database->getConnection();

// Request ka method (GET, POST, PUT, etc.) check karna
$method = $_SERVER['REQUEST_METHOD'];

// Method ke basis par action perform karna
switch ($method) {
    case 'GET':
        try {
            // URL se order ID get karna, agar available hai
            $orderId = $_GET['id'] ?? null;
            
            if ($orderId) {
                // --- EK SPECIFIC ORDER KI DETAILS FETCH KARNA ---
                $stmt = $db->prepare("
                    SELECT o.*, u.name as user_name, u.email as user_email,
                           a.label as address_label, a.address_line1, a.address_line2, a.city, a.state, a.postal_code
                    FROM orders o
                    JOIN users u ON o.user_id = u.id
                    LEFT JOIN addresses a ON o.shipping_address_id = a.id
                    WHERE o.id = :id
                ");
                $stmt->bindParam(':id', $orderId, PDO::PARAM_STR);
                $stmt->execute();
                $order = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($order) {
                    // Order ke items fetch karna with variant details
                    $itemsStmt = $db->prepare("
                        SELECT oi.*, p.name as product_name, p.brand, p.sku, p.description, pi.url as image_url,
                               pv.variant_name, pv.price_diff as variant_price_diff, 
                               pv.stock as variant_stock, 
                               pc.name as category_name
                        FROM order_items oi
                        JOIN products p ON oi.product_id = p.id
                        LEFT JOIN product_images pi ON p.id = pi.product_id AND pi.position = 0
                        LEFT JOIN product_variants pv ON oi.variant_id = pv.id
                        LEFT JOIN categories pc ON p.category_id = pc.id
                        WHERE oi.order_id = :id
                    ");
                    $itemsStmt->bindParam(':id', $orderId, PDO::PARAM_STR);
                    $itemsStmt->execute();
                    $items = $itemsStmt->fetchAll(PDO::FETCH_ASSOC);
                    
                    // Har item mein zaroori details add karna
                    foreach ($items as &$item) {
                        if ($item['variant_name']) {
                            $item['has_variant'] = true;
                            $item['display_name'] = $item['product_name'] . ' (' . $item['variant_name'] . ')';
                            $item['variant_info'] = [
                                'name' => $item['variant_name'],
                                'price_diff' => $item['variant_price_diff'],
                                'stock' => $item['variant_stock']
                            ];
                        } else {
                            $item['has_variant'] = false;
                            $item['display_name'] = $item['product_name'];
                            $item['variant_info'] = null;
                        }
                        
                        $basePrice = floatval($item['unit_price']);
                        $priceDiff = floatval($item['variant_price_diff'] ?? 0);
                        $item['actual_unit_price'] = $basePrice + $priceDiff;
                        $item['category'] = $item['category_name'] ?? 'Uncategorized';
                    }
                    
                    $order['items'] = $items;

                    // === PAYMENT CONFIRMATION LINK LOGIC ===
                    if ($order['payment_method'] === 'cash_on_delivery' && 
                        $order['payment_status'] === 'pending' && 
                        !empty($order['payment_confirmation_token'])) {
                        
                        // IMPORTANT: 'https://backmobile.rihancsccenter.in' ko apni actual website ke domain se replace karein
                        $baseUrl = "https://backmobile.rihancsccenter.in/api/admin/confirm_payment.php";
                        $order['payment_confirmation_link'] = $baseUrl . '?token=' . $order['payment_confirmation_token'];
                    } else {
                        $order['payment_confirmation_link'] = null;
                    }

                    // === ORDER MANAGEMENT LINK LOGIC ===
                    // Since management_token column doesn't exist, we'll use order ID for management
                    $mgmtBaseUrl = "https://backmobile.rihancsccenter.in/api/admin/manage_order.php";
                    $order['management_link'] = $mgmtBaseUrl . '?order_id=' . $order['id'];
                }
                
                http_response_code($order ? 200 : 404);
                echo json_encode(['success' => !!$order, 'order' => $order]);

            } else {
                // --- SAARE ORDERS KI LIST FETCH KARNA ---
                $statusFilter = $_GET['status'] ?? '';
                $whereClause = '';
                $params = [];
                
                if ($statusFilter) {
                    $whereClause = 'WHERE o.status = :status';
                    $params[':status'] = $statusFilter;
                }
                
                $stmt = $db->prepare("
                    SELECT o.id, o.total_price, o.status, o.created_at, o.payment_method, o.payment_status,
                           u.name as user_name, u.email as user_email, u.phone as user_phone,
                           a.city, a.state,
                           COUNT(oi.id) as item_count,
                           SUM(CASE WHEN oi.variant_id IS NOT NULL THEN 1 ELSE 0 END) as variant_items_count
                    FROM orders o
                    JOIN users u ON o.user_id = u.id
                    LEFT JOIN addresses a ON o.shipping_address_id = a.id
                    LEFT JOIN order_items oi ON o.id = oi.order_id
                    $whereClause
                    GROUP BY o.id
                    ORDER BY o.created_at DESC
                ");
                
                foreach ($params as $key => $value) {
                    $stmt->bindParam($key, $value);
                }
                
                $stmt->execute();
                $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                echo json_encode(['success' => true, 'orders' => $orders]);
            }

        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
        }
        break;

    case 'PUT':
        // Order ka status update karne ke liye
        $data = json_decode(file_get_contents('php://input'), true);
        
        $orderId = $data['id'] ?? null;
        $status = $data['status'] ?? null;

        if (!$orderId || !$status) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Order ID aur status, dono zaroori hain']);
            exit;
        }
        
        // Allowed statuses according to database enum
        $allowedStatuses = ['pending', 'confirmed', 'processing', 'shipped', 'delivered', 'cancelled'];
        if (!in_array($status, $allowedStatuses)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid status. Allowed: ' . implode(', ', $allowedStatuses)]);
            exit;
        }
        
        try {
            $stmt = $db->prepare("UPDATE orders SET status = :status, updated_at = CURRENT_TIMESTAMP WHERE id = :id");
            $stmt->bindParam(':status', $status, PDO::PARAM_STR);
            $stmt->bindParam(':id', $orderId, PDO::PARAM_STR);
            $stmt->execute();
            
            if ($stmt->rowCount() === 0) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Order nahi mila']);
                exit;
            }
            
            // Agar order 'delivered' hai, to payment 'paid' kar dein (COD ke liye)
            if ($status === 'delivered') {
                $paymentStmt = $db->prepare("UPDATE orders SET payment_status = 'paid' WHERE id = :id AND payment_method = 'cash_on_delivery'");
                $paymentStmt->bindParam(':id', $orderId, PDO::PARAM_STR);
                $paymentStmt->execute();
            }
            
            http_response_code(200);
            echo json_encode(['success' => true, 'message' => 'Order status successfully update ho gaya']);

        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Order update nahi ho paaya: ' . $e->getMessage()]);
        }
        break;

    default:
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Yeh Method allowed nahi hai']);
        break;
}
?>