<?php
// FILE: api/admin/delivery.php (JSON API Version)

// --- SETUP AND HEADERS ---
ini_set('display_errors', 1);
error_reporting(E_ALL);
// Sabse zaroori line: Browser ko batata hai ki response JSON hai
header("Content-Type: application/json; charset=UTF-8");

require_once '../config/cors.php';

// --- DATABASE CONNECTION (DIRECTLY IN THIS FILE) ---
$db_host = "51.178.131.16";
$db_user = "rihancsc_shivam";
$db_pass = "Shivam@1924";
$db_name = "rihancsc_mobileshop";

mysqli_report(MYSQLI_REPORT_OFF);
$db = new mysqli($db_host, $db_user, $db_pass, $db_name);

if ($db->connect_error) {
    http_response_code(503);
    echo json_encode(['success' => false, 'message' => 'Database Connection Error: ' . $db->connect_error]);
    exit; // Script ko yahin rok dein
}
$db->set_charset("utf8");

// --- INITIALIZE VARIABLES ---
$method = $_SERVER['REQUEST_METHOD'];
$token = $_GET['token'] ?? null;

// Agar token GET mein nahi hai, to POST body se lene ki koshish karein
if (empty($token) && $method !== 'GET') {
    $input = json_decode(file_get_contents('php://input'), true);
    $token = $input['token'] ?? null;
}

if (empty($token)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Delivery token is required.']);
    exit;
}

// --- API ROUTING ---
try {
    if ($method === 'GET') {
        // GET request se order details fetch karein
        handleGetRequest($db, $token);
    } elseif ($method === 'POST' || $method === 'PUT') {
        // POST ya PUT request se order update karein
        $input = json_decode(file_get_contents('php://input'), true);
        handleUpdateRequest($db, $token, $input);
    } else {
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Method not allowed.']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'A critical error occurred: ' . $e->getMessage()]);
}

// --- FUNCTION TO GET ORDER DETAILS ---
function handleGetRequest($db, $token) {
    $stmt = $db->prepare("
        SELECT o.id, o.total_price, o.status, o.payment_status, o.payment_method,
               o.delivery_boy_name, u.name as customer_name, u.phone as customer_phone,
               a.address_line1, 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.delivery_token = ? ORDER BY o.created_at ASC
    ");
    $stmt->bind_param('s', $token);
    $stmt->execute();
    $result = $stmt->get_result();
    $orders = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    if (empty($orders)) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'No orders found for this token.']);
        exit;
    }

    foreach ($orders as &$order) {
        $itemsStmt = $db->prepare("
            SELECT oi.quantity, p.name as product_name, p.brand, pv.variant_name
            FROM order_items oi
            JOIN products p ON oi.product_id = p.id
            LEFT JOIN product_variants pv ON oi.variant_id = pv.id
            WHERE oi.order_id = ?
        ");
        $itemsStmt->bind_param('s', $order['id']);
        $itemsStmt->execute();
        $itemsResult = $itemsStmt->get_result();
        $order['items'] = $itemsResult->fetch_all(MYSQLI_ASSOC);
        $itemsStmt->close();
    }

    echo json_encode(['success' => true, 'data' => $orders]);
}

// --- FUNCTION TO UPDATE ORDER ---
function handleUpdateRequest($db, $token, $input) {
    $action = $input['action'] ?? null;
    if (!$action) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Action is required in the request body.']);
        exit;
    }

    $db->begin_transaction();
    try {
        $stmt = null;
        $message = '';
        
        switch ($action) {
            case 'confirm_single_delivery':
                $orderId = $input['order_id'] ?? null;
                if (!$orderId) throw new Exception("order_id is required.");
                $sql = "UPDATE orders SET status = 'delivered', payment_status = IF(payment_method = 'cash_on_delivery', 'paid', payment_status) WHERE id = ? AND delivery_token = ?";
                $stmt = $db->prepare($sql);
                $stmt->bind_param('ss', $orderId, $token);
                $message = "Order " . substr($orderId, -8) . " marked as delivered.";
                break;
            
            // Yahan aap aur actions (jaise 'report_issue') add kar sakte hain

            default:
                throw new Exception("Invalid action provided.");
        }
        
        $stmt->execute();
        $affected_rows = $stmt->affected_rows;
        $stmt->close();

        if ($affected_rows > 0) {
            $db->commit();
            echo json_encode(['success' => true, 'message' => $message]);
        } else {
            $db->rollback();
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Order not found or no update was needed.']);
        }
    } catch (Exception $e) {
        $db->rollback();
        throw $e; 
    }
}
?>