<?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";

/* -----------------------------------------------------------
   SQL TABLE STRUCTURE:

   CREATE TABLE `options` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
     `option` varchar(255) NOT NULL,
     `option_slug` varchar(255) NOT NULL,
     `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
     `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
     PRIMARY KEY (`id`)
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
----------------------------------------------------------- */

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

/* -------------------------------
   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 `options` WHERE id=?");
            mysqli_stmt_bind_param($stmt, "i", $id);
            mysqli_stmt_execute($stmt);
            $res = mysqli_stmt_get_result($stmt);
            $data = mysqli_fetch_assoc($res);
            echo json_encode(["status" => "success", "data" => $data]);
            mysqli_stmt_close($stmt);
        } else {
            $res = mysqli_query($conn, "SELECT * FROM `options` ORDER BY created_at DESC");
            $rows = [];
            while ($row = mysqli_fetch_assoc($res)) {
                $rows[] = $row;
            }
            echo json_encode(["status" => "success", "data" => $rows]);
        }
        break;

    /* -------------------------------
       POST (CREATE, UPDATE, CSV UPLOAD)
    ------------------------------- */
    case "POST":

        // --- CSV UPLOAD ---
        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, 1000, ",")) !== false) {
                if ($row++ === 0)
                    continue; // Skip header

                // Mapping: Column 0 = option, Column 1 = option_slug
                $id = sanitize($data[0] ?? '');
                $opt = sanitize($data[1] ?? '');
                $slug = sanitize($data[2] ?? '');

                if (empty($slug) && !empty($opt)) {
                    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $opt)));
                }

                if (!empty($opt)) {
                    $stmt = mysqli_prepare($conn, "INSERT INTO `options` (`id`,`option`, option_slug) VALUES (?,?, ?)");
                    mysqli_stmt_bind_param($stmt, "iss", $id, $opt,$slug);
                    if (mysqli_stmt_execute($stmt)) {
                        $inserted++;
                    }
                    mysqli_stmt_close($stmt);
                }
            }
            fclose($handle);
            echo json_encode(["status" => "success", "inserted" => $inserted]);
            exit;
        }

        // --- SINGLE CREATE / UPDATE ---
        $id = intval($_POST['id'] ?? 0);
        $opt = sanitize($_POST['option'] ?? '');
        $slug = sanitize($_POST['option_slug'] ?? '');

        // Auto-generate slug if not provided
        if (empty($slug) && !empty($opt)) {
            $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $opt)));
        }

        if ($id > 0) {
            // Update
            $stmt = mysqli_prepare($conn, "UPDATE `options` SET `option`=?, option_slug=?, updated_at=NOW() WHERE id=?");
            mysqli_stmt_bind_param($stmt, "ssi", $opt, $slug, $id);
            $msg = "Option updated";
        } else {
            // Insert
            $stmt = mysqli_prepare($conn, "INSERT INTO `options` (`option`, option_slug) VALUES (?, ?)");
            mysqli_stmt_bind_param($stmt, "ss", $opt, $slug);
            $msg = "Option added";
        }

        if (mysqli_stmt_execute($stmt)) {
            echo json_encode(["status" => "success", "message" => $msg]);
        } else {
            echo 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 `options` WHERE id=?");
        mysqli_stmt_bind_param($stmt, "i", $id);

        if (mysqli_stmt_execute($stmt)) {
            echo json_encode(["status" => "success"]);
        } else {
            echo json_encode(["status" => "error", "message" => mysqli_error($conn)]);
        }
        mysqli_stmt_close($stmt);
        break;

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

mysqli_close($conn);
?>