<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, 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";

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

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

function uploadBrandLogo($file)
{
    $uploadDir = "../../assets/brands/";
    $publicPath = "assets/brands/";

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

    $allowedTypes = ["jpg", "jpeg", "png", "gif", "webp"];
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

    if (!in_array($ext, $allowedTypes)) {
        return ["status" => false, "message" => "Invalid image type"];
    }

    $fileName = "BRAND_" . time() . "_" . rand(1000, 9999) . "." . $ext;
    $targetPath = $uploadDir . $fileName;

    if (move_uploaded_file($file["tmp_name"], $targetPath)) {
        return [
            "status" => true,
            "file_url" => BASE_URL . $publicPath . $fileName
        ];
    }

    return ["status" => false, "message" => "Image upload failed"];
}

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

switch ($method) {

    /* -------------------------------
    GET ALL BRANDS
    ------------------------------- */
    case "GET":
        $res = mysqli_query($conn, "SELECT * FROM brands ORDER BY id DESC");
        $brands = [];

        while ($row = mysqli_fetch_assoc($res)) {
            $row['brand_logo'] = $row['brand_logo'] ?: null;
            $brands[] = $row;
        }

        echo json_encode([
            "status" => "success",
            "data" => $brands
        ]);
        break;

    /* -------------------------------
    CREATE / UPDATE BRAND OR UPLOAD CSV
    ------------------------------- */
    case "POST":

        // ---------- CSV UPLOAD ----------
        // ---------- CSV UPLOAD ----------
        if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] === 0) {

            $file = $_FILES['csv_file']['tmp_name'];
            $handle = fopen($file, "r");

            if (!$handle) {
                echo json_encode(["status" => "error", "message" => "Failed to open CSV file"]);
                exit;
            }

            $rowCount = 0;
            $results = [];
            while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                // Skip header row
                if ($rowCount === 0) {
                    $rowCount++;
                    continue;
                }

                $brand_name = sanitize($data[0] ?? '');
                $status = sanitize($data[1] ?? 'active');
                $brand_logo = sanitize($data[2] ?? null); // <-- CSV logo path

                if (!$brand_name) {
                    $results[] = ["row" => $rowCount, "status" => "error", "message" => "Brand name missing"];
                    $rowCount++;
                    continue;
                }

                // Optional: prepend BASE_URL if not a full URL
                if ($brand_logo && !str_starts_with($brand_logo, "http")) {
                    $brand_logo = BASE_URL . ltrim($brand_logo, "/");
                }

                // Insert brand
                $stmt = mysqli_prepare(
                    $conn,
                    "INSERT INTO brands (brand_name,brand_logo, status, created_at) VALUES (?, ?, ?, NOW())"
                );
                mysqli_stmt_bind_param($stmt, "sss", $brand_name, $status, $brand_logo);
                $exec = mysqli_stmt_execute($stmt);
                mysqli_stmt_close($stmt);

                $results[] = [
                    "row" => $rowCount,
                    "status" => $exec ? "success" : "error",
                    "message" => $exec ? "Brand added" : "Failed to add brand"
                ];

                $rowCount++;
            }

            fclose($handle);

            echo json_encode(["status" => "success", "message" => "CSV processed", "results" => $results]);
            exit;
        }


        // ---------- SINGLE BRAND CREATE / UPDATE ----------
        $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
        $brand_name = isset($_POST['brand_name']) ? sanitize($_POST['brand_name']) : null;
        $status = isset($_POST['status']) ? sanitize($_POST['status']) : "active";

        if (!$brand_name) {
            echo json_encode(["status" => "error", "message" => "Brand name is required"]);
            exit;
        }

        $brand_logo = null;

        if (isset($_FILES['brand_logo']) && $_FILES['brand_logo']['error'] === 0) {
            $upload = uploadBrandLogo($_FILES['brand_logo']);

            if (!$upload['status']) {
                echo json_encode(["status" => "error", "message" => $upload['message']]);
                exit;
            }

            $brand_logo = $upload['file_url'];
        }

        /* ---------- UPDATE ---------- */
        if ($id > 0) {

            // Remove old logo if new one uploaded
            if ($brand_logo) {
                $res = mysqli_query($conn, "SELECT brand_logo FROM brands WHERE id=$id");
                if ($res && mysqli_num_rows($res) > 0) {
                    $oldLogoUrl = mysqli_fetch_assoc($res)['brand_logo'];
                    if ($oldLogoUrl) {
                        $oldFile = basename($oldLogoUrl);
                        $oldPath = "../../assets/brands/" . $oldFile;
                        if (file_exists($oldPath))
                            unlink($oldPath);
                    }
                }

                $stmt = mysqli_prepare(
                    $conn,
                    "UPDATE brands SET brand_name=?, status=?, brand_logo=?, updated_at=NOW() WHERE id=?"
                );
                mysqli_stmt_bind_param($stmt, "sssi", $brand_name, $status, $brand_logo, $id);

            } else {
                $stmt = mysqli_prepare(
                    $conn,
                    "UPDATE brands SET brand_name=?, status=?, updated_at=NOW() WHERE id=?"
                );
                mysqli_stmt_bind_param($stmt, "ssi", $brand_name, $status, $id);
            }

            $message = "Brand updated successfully";

            /* ---------- CREATE ---------- */
        } else {

            $stmt = mysqli_prepare(
                $conn,
                "INSERT INTO brands (brand_name, brand_logo, status, created_at) VALUES (?,?,?,NOW())"
            );
            mysqli_stmt_bind_param($stmt, "sss", $brand_name, $brand_logo, $status);
            $message = "Brand added successfully";
        }

        if (mysqli_stmt_execute($stmt)) {
            echo json_encode(["status" => "success", "message" => $message]);
        } else {
            echo json_encode(["status" => "error", "message" => "Failed to save brand"]);
        }

        mysqli_stmt_close($stmt);
        break;

    /* -------------------------------
    DELETE BRAND
    ------------------------------- */
    case "DELETE":

        parse_str(file_get_contents("php://input"), $_DELETE);
        $id = isset($_DELETE["id"]) ? intval($_DELETE["id"]) : 0;

        if ($id <= 0) {
            echo json_encode(["status" => "error", "message" => "Invalid brand ID"]);
            exit;
        }

        $res = mysqli_query($conn, "SELECT brand_logo FROM brands WHERE id=$id");
        if ($res && mysqli_num_rows($res) > 0) {
            $logoUrl = mysqli_fetch_assoc($res)['brand_logo'];
            if ($logoUrl) {
                $fileName = basename($logoUrl);
                $path = "../../assets/brands/" . $fileName;
                if (file_exists($path))
                    unlink($path);
            }
        }

        $stmt = mysqli_prepare($conn, "DELETE FROM brands WHERE id=?");
        mysqli_stmt_bind_param($stmt, "i", $id);

        if (mysqli_stmt_execute($stmt)) {
            echo json_encode(["status" => "success", "message" => "Brand deleted successfully"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Failed to delete brand"]);
        }

        mysqli_stmt_close($stmt);
        break;

    /* -------------------------------
    OPTIONS
    ------------------------------- */
    case "OPTIONS":
        http_response_code(200);
        break;

    default:
        http_response_code(405);
        echo json_encode(["status" => "error", "message" => "Method not allowed"]);
        break;
}

mysqli_close($conn);
