<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header("Content-Type: application/json; charset=UTF-8");

require_once "../../dbcon.php";

define('BASE_URL', 'https://bmbackend.featuredeveloper.com/');

/* -------------------------------
HELPERS
------------------------------- */
function sanitize($data)
{
    global $conn;
    return htmlspecialchars(strip_tags(mysqli_real_escape_string($conn, $data)));
}

/* Generate Stock Number (BM-001, BM-002...) */
function generateStockNo()
{
    global $conn;
    $res = mysqli_query($conn, "SELECT stock_no FROM cars ORDER BY id DESC LIMIT 1");
    $row = mysqli_fetch_assoc($res);

    if ($row && preg_match('/BM-(\d+)/', $row['stock_no'], $m)) {
        $num = intval($m[1]) + 1;
    } else {
        $num = 1;
    }
    return 'BM-' . str_pad($num, 3, '0', STR_PAD_LEFT);
}

/* Upload Car Images */
function uploadCarImage($file, $prefix = "CAR")
{
    if (!isset($file) || $file['error'] !== 0)
        return null;

    $uploadDir = "../../assets/cars/";
    $publicPath = "assets/cars/";

    if (!is_dir($uploadDir))
        mkdir($uploadDir, 0777, true);

    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $fileName = $prefix . "_" . time() . "_" . rand(1000, 9999) . "." . $ext;

    if (move_uploaded_file($file['tmp_name'], $uploadDir . $fileName)) {
        return BASE_URL . $publicPath . $fileName;
    }
    return null;
}

/* -------------------------------
REQUEST HANDLER
------------------------------- */
$method = $_SERVER["REQUEST_METHOD"];

switch ($method) {

    /* -------------------------------
    GET
    ------------------------------- */
    case "GET":
        if (isset($_GET['id'])) {
            $id = intval($_GET['id']);
            $stmt = mysqli_prepare($conn, "SELECT * FROM cars WHERE id=?");
            mysqli_stmt_bind_param($stmt, "i", $id);
            mysqli_stmt_execute($stmt);
            $res = mysqli_stmt_get_result($stmt);
            echo json_encode(["status" => "success", "data" => mysqli_fetch_assoc($res)]);
            mysqli_stmt_close($stmt);
        } else {
            $res = mysqli_query($conn, "SELECT * FROM cars ORDER BY created_at DESC");
            $cars = [];
            while ($row = mysqli_fetch_assoc($res))
                $cars[] = $row;
            echo json_encode(["status" => "success", "data" => $cars]);
        }
        break;

    /* -------------------------------
    POST (CSV + SINGLE INSERT/UPDATE)
    ------------------------------- */
    case "POST":

        /* -------- CSV IMPORT -------- */
        /* -------- CSV IMPORT -------- */
        if (isset($_FILES['csv_file'])) {
            $handle = fopen($_FILES['csv_file']['tmp_name'], "r");
            if (!$handle)
                exit(json_encode(["status" => "error", "message" => "CSV open failed"]));

            $row = 0;
            $inserted = 0;
            while (($data = fgetcsv($handle, 5000, ",")) !== false) {
                if ($row++ === 0)
                    continue; // skip header

                // Map CSV columns to variables (MATCHING SQL LAYOUT ORDER)
                $brand_id = intval($data[0] ?? 0);
                $stock_no = sanitize($data[1] ?? '');
                $name = sanitize($data[2] ?? '');
                $make_region = sanitize($data[3] ?? '');
                $chassis_no = sanitize($data[4] ?? '');
                $category = sanitize($data[5] ?? '');
                $model = sanitize($data[6] ?? '');
                $make_year = sanitize($data[7] ?? '');
                $fuel_type = sanitize($data[8] ?? '');
                $transmission = sanitize($data[9] ?? '');
                $steering = sanitize($data[10] ?? '');
                $doors = sanitize($data[11] ?? '');
                $seat = sanitize($data[12] ?? '');
                $driver_type = sanitize($data[13] ?? '');
                $body_type = sanitize($data[14] ?? '');
                $color = sanitize($data[15] ?? '');
                $engine = sanitize($data[16] ?? '');
                $mileage = sanitize($data[17] ?? '');
                $budget = (double) ($data[18] ?? 0);
                $price = (double) ($data[19] ?? 0);

                // Images (columns 20 to 29)
                $images = [];
                for ($i = 1; $i <= 10; $i++) {
                    $images[$i] = sanitize($data[19 + $i] ?? '');
                }

                $status = sanitize($data[30] ?? 'available');
                $created_by = intval($data[31] ?? 0);
                $dimensions = sanitize($data[32] ?? '');
                $m3 = sanitize($data[33] ?? '');
                $options = sanitize($data[34] ?? '');
                $countries = sanitize($data[35] ?? '');

                // Prepare INSERT statement (MATCHING SQL LAYOUT ORDER)
                $stmt = mysqli_prepare($conn, "
INSERT INTO cars (
    brand_id, stock_no, name, make_region, chassis_no, category, model, make_year,
    fuel_type, transmission, steering, doors, seat, driver_type, body_type, color,
    engine, mileage, budget, price,
    image1,image2,image3,image4,image5,image6,image7,image8,image9,image10,
    status, created_by, dimensions, m3, options, countries
) VALUES (
    ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?
)
");

                if (!$stmt) {
                    exit(json_encode(["status" => "error", "message" => "Prepare failed: " . mysqli_error($conn)]));
                }

                // Bind parameters (36 fields)
                mysqli_stmt_bind_param(
                    $stmt,
                    "isssssssssssssssssddsssssssssssissss",
                    $brand_id,
                    $stock_no,
                    $name,
                    $make_region,
                    $chassis_no,
                    $category,
                    $model,
                    $make_year,
                    $fuel_type,
                    $transmission,
                    $steering,
                    $doors,
                    $seat,
                    $driver_type,
                    $body_type,
                    $color,
                    $engine,
                    $mileage,
                    $budget,
                    $price,
                    $images[1],
                    $images[2],
                    $images[3],
                    $images[4],
                    $images[5],
                    $images[6],
                    $images[7],
                    $images[8],
                    $images[9],
                    $images[10],
                    $status,
                    $created_by,
                    $dimensions,
                    $m3,
                    $options,
                    $countries
                );

                if (mysqli_stmt_execute($stmt))
                    $inserted++;
                else
                    echo "Insert error: " . mysqli_error($conn);

                mysqli_stmt_close($stmt);
            }

            fclose($handle);
            echo json_encode(["status" => "success", "inserted" => $inserted]);
            exit;
        }


        /* -------- SINGLE INSERT / UPDATE -------- */
        $id = intval($_POST['id'] ?? 0);
        $brand_id = intval($_POST['brand_id'] ?? 0);
        $stock_no = $id > 0 ? sanitize($_POST['stock_no']) : generateStockNo();

        $name = sanitize($_POST['name'] ?? '');
        $make_region = sanitize($_POST['make_region'] ?? '');
        $chassis_no = sanitize($_POST['chassis_no'] ?? '');
        $category = sanitize($_POST['category'] ?? '');
        $model = sanitize($_POST['model'] ?? '');
        $make_year = sanitize($_POST['make_year'] ?? '');
        $fuel_type = sanitize($_POST['fuel_type'] ?? '');
        $transmission = sanitize($_POST['transmission'] ?? '');
        $steering = sanitize($_POST['steering'] ?? '');
        $doors = sanitize($_POST['doors'] ?? '');
        $seat = sanitize($_POST['seat'] ?? '');
        $driver_type = sanitize($_POST['driver_type'] ?? '');
        $body_type = sanitize($_POST['body_type'] ?? '');
        $color = sanitize($_POST['color'] ?? '');
        $engine = sanitize($_POST['engine'] ?? '');
        $mileage = sanitize($_POST['mileage'] ?? '');
        $budget = (double) ($_POST['budget'] ?? 0);
        $price = (double) ($_POST['price'] ?? 0);
        $dimensions = sanitize($_POST['dimensions'] ?? '');
        $m3 = sanitize($_POST['m3'] ?? '');
        $status = sanitize($_POST['status'] ?? 'available');
        $created_by = intval($_POST['created_by'] ?? 0);

        // Handle Options Array
        $options = '';
        if (isset($_POST['options'])) {
            if (is_array($_POST['options'])) {
                $options = implode(',', $_POST['options']);
            } else {
                $options = sanitize($_POST['options']);
            }
        }

        // Handle Countries Array
        $countries = '';
        if (isset($_POST['countries'])) {
            if (is_array($_POST['countries'])) {
                $countries = implode(',', $_POST['countries']);
            } else {
                $countries = sanitize($_POST['countries']);
            }
        }

        $images = [];
        for ($i = 1; $i <= 10; $i++)
            $images[$i] = uploadCarImage($_FILES["image$i"] ?? null);

        if ($id > 0) {
            $old = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM cars WHERE id=$id"));
            for ($i = 1; $i <= 10; $i++)
                if (!$images[$i])
                    $images[$i] = $old["image$i"];

            $stmt = mysqli_prepare($conn, "
                UPDATE cars SET
                    brand_id=?, stock_no=?, name=?, make_region=?, chassis_no=?, category=?, model=?, make_year=?,
                    fuel_type=?, transmission=?, steering=?, doors=?, seat=?, driver_type=?, body_type=?, color=?,
                    engine=?, mileage=?, budget=?, price=?, 
                    image1=?,image2=?,image3=?,image4=?,image5=?,image6=?,image7=?,image8=?,image9=?,image10=?,
                    status=?, dimensions=?, m3=?, options=?, countries=?, updated_at=NOW()
                WHERE id=?
            ");

            mysqli_stmt_bind_param(
                $stmt,
                "isssssssssssssssssddsssssssssssssssi",
                $brand_id,
                $stock_no,
                $name,
                $make_region,
                $chassis_no,
                $category,
                $model,
                $make_year,
                $fuel_type,
                $transmission,
                $steering,
                $doors,
                $seat,
                $driver_type,
                $body_type,
                $color,
                $engine,
                $mileage,
                $budget,
                $price,
                $images[1],
                $images[2],
                $images[3],
                $images[4],
                $images[5],
                $images[6],
                $images[7],
                $images[8],
                $images[9],
                $images[10],
                $status,
                $dimensions,
                $m3,
                $options,
                $countries,
                $id
            );

            $msg = "Car updated";

        } else {
            $stmt = mysqli_prepare($conn, "
INSERT INTO cars (
    brand_id, stock_no, name, make_region, chassis_no, category, model, make_year,
    fuel_type, transmission, steering, doors, seat, driver_type, body_type, color,
    engine, mileage, budget, price,
    image1,image2,image3,image4,image5,image6,image7,image8,image9,image10,
    status, created_by, dimensions, m3, options, countries
) VALUES (
    ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?
)
");

            mysqli_stmt_bind_param(
                $stmt,
                "isssssssssssssssssddsssssssssssissss",
                $brand_id,
                $stock_no,
                $name,
                $make_region,
                $chassis_no,
                $category,
                $model,
                $make_year,
                $fuel_type,
                $transmission,
                $steering,
                $doors,
                $seat,
                $driver_type,
                $body_type,
                $color,
                $engine,
                $mileage,
                $budget,
                $price,
                $images[1],
                $images[2],
                $images[3],
                $images[4],
                $images[5],
                $images[6],
                $images[7],
                $images[8],
                $images[9],
                $images[10],
                $status,
                $created_by,
                $dimensions,
                $m3,
                $options,
                $countries
            );

            $msg = "Car added";
        }

        mysqli_stmt_execute($stmt)
            ? print json_encode(["status" => "success", "message" => $msg, "stock_no" => $stock_no])
            : print json_encode(["status" => "error", "message" => "DB error: " . mysqli_error($conn)]);

        mysqli_stmt_close($stmt);
        break;

    /* -------------------------------
    DELETE
    ------------------------------- */
    case "DELETE":
        parse_str(file_get_contents("php://input"), $_DELETE);
        $id = intval($_DELETE['id'] ?? 0);
        $stmt = mysqli_prepare($conn, "DELETE FROM cars WHERE id=?");
        mysqli_stmt_bind_param($stmt, "i", $id);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_close($stmt);
        echo json_encode(["status" => "success"]);
        break;

    case "OPTIONS":
        http_response_code(200);
        break;
}

mysqli_close($conn);
?>