<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once "includes/auth.php";
ensure_manager();
require_once "includes/functions.php";

$restaurant_id = $_SESSION['restaurant_id'];

/* =============================================================
   1) UPLOAD IMAGE (CORRECT FIXED PATH)
============================================================= */
function upload_image($file, $folder)
{
    if (!isset($file) || $file['error'] !== 0) {
        return null;
    }

    // نحقن الملف في $_FILES ليستعمله upload_custom
    $_FILES['__proxy'] = $file;

    // استدعاء الفانكشن الموحدة
    return upload_custom('__proxy', ucfirst($folder));
}

/* =============================================================
   2) GET ACTIVE LANGUAGES FOR THIS RESTAURANT
============================================================= */
function get_restaurant_langs($restaurant_id)
{
    $langs = fetch_all("
        SELECT l.code 
        FROM restaurant_languages rl
        JOIN languages l ON l.id = rl.language_id
        WHERE rl.restaurant_id = ? AND rl.active = 1
    ", [$restaurant_id]);

    return $langs ? array_column($langs, 'code') : ['ar'];
}

/* =============================================================
   3) BUILD IMAGE URL
============================================================= */
function build_image_url_json($image, $folder)
{
    if (!$image) return "../assets/no-image.png";
    if (strpos($image, 'uploads/') === 0) {
        return "../" . $image;
    }
    return "../uploads/$folder/" . $image;
}

/* =============================================================
   4) HANDLE JSON (REORDER ONLY)
============================================================= */
if (!empty($_SERVER['CONTENT_TYPE']) && strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false) {

    $data = json_decode(file_get_contents("php://input"), true);

    if (!$data || !isset($data['action']) || $data['action'] !== 'reorder') {
        echo json_encode(['error' => 'Invalid JSON action']);
        exit;
    }

    if ($data['type'] === "category") {
        foreach ($data['list'] as $row) {
            db()->prepare("
                UPDATE categories 
                SET ordering = ? 
                WHERE id = ? AND restaurant_id = ?
            ")->execute([$row['pos'], $row['id'], $restaurant_id]);
        }
        echo json_encode(["success" => true]);
        exit;
    }

    if ($data['type'] === "item") {
        foreach ($data['list'] as $row) {
            db()->prepare("
                UPDATE items 
                SET ordering = ?, category_id = ?
                WHERE id = ? AND restaurant_id = ?
            ")->execute([$row['pos'], $row['category'], $row['id'], $restaurant_id]);
        }
        echo json_encode(["success" => true]);
        exit;
    }

    echo json_encode(['error' => 'Invalid reorder type']);
    exit;
}

/* =============================================================
   5) NORMAL POST ACTIONS
============================================================= */

$action = $_POST['action'] ?? null;


/* ---------- GET CATEGORY ---------- */
if ($action === 'get_category') {

    $id = intval($_POST['id'] ?? 0);

    $cat = fetch_one("
        SELECT * FROM categories 
        WHERE id = ? AND restaurant_id = ?
    ", [$id, $restaurant_id]);

    if (!$cat) {
        echo json_encode(['error' => 'not_found']);
        exit;
    }

    $cat['image_url'] = build_image_url_json($cat['image'], 'categories');

    echo json_encode($cat);
    exit;
}


/* ---------- GET ITEM ---------- */
if ($action === 'get_item') {

    $id = intval($_POST['id'] ?? 0);

    $item = fetch_one("
        SELECT * FROM items 
        WHERE id = ? AND restaurant_id = ?
    ", [$id, $restaurant_id]);

    if (!$item) {
        echo json_encode(['error' => 'not_found']);
        exit;
    }

    $item['image_url'] = build_image_url_json($item['image'], 'items');
    $item['price']     = $item['base_price'];

    $langs = get_restaurant_langs($restaurant_id);
    foreach ($langs as $l) {
        $item["name_$l"]        = $item["name_$l"] ?? "";
        $item["description_$l"] = $item["description_$l"] ?? "";
    }

    echo json_encode($item);
    exit;
}


/* =============================================================
   6) SWITCH FOR CRUD
============================================================= */

switch ($action) {

/* ---------- ADD CATEGORY ---------- */
case "add_category":

    $img   = upload_image($_FILES['image'], "categories");
    $langs = get_restaurant_langs($restaurant_id);

    $fields = "restaurant_id, image, ordering";
    $values = "?, ?, ?";
    $params = [$restaurant_id, $img, 9999];

    foreach ($langs as $l) {
        $fields .= ", name_$l";
        $values .= ", ?";
        $params[] = $_POST["name_$l"] ?? "";
    }

    db()->prepare("INSERT INTO categories ($fields) VALUES ($values)")
       ->execute($params);

    header("Location: menu_builder.php");
    exit;


/* ---------- EDIT CATEGORY ---------- */
case "edit_category":

    $id = intval($_POST["id"]);

    $old = fetch_one("
        SELECT image FROM categories 
        WHERE id = ? AND restaurant_id = ?
    ", [$id, $restaurant_id]);

   $new_img = upload_custom("image", "Categories", $old['image']);


    $langs = get_restaurant_langs($restaurant_id);

    $sql    = "UPDATE categories SET image = ?";
    $params = [$new_img];

    foreach ($langs as $l) {
        $sql .= ", name_$l = ?";
        $params[] = $_POST["name_$l"] ?? "";
    }

    $sql .= " WHERE id = ? AND restaurant_id = ?";
    $params[] = $id;
    $params[] = $restaurant_id;

    db()->prepare($sql)->execute($params);

    header("Location: menu_builder.php");
    exit;


/* ---------- DELETE CATEGORY ---------- */
case "delete_category":

    $id = intval($_POST["id"]);

    db()->prepare("DELETE FROM items WHERE category_id = ? AND restaurant_id = ?")
       ->execute([$id, $restaurant_id]);

    db()->prepare("DELETE FROM categories WHERE id = ? AND restaurant_id = ?")
       ->execute([$id, $restaurant_id]);

    echo "1";
    exit;


/* ---------- ADD ITEM ---------- */
case "add_item":

    $cat_id = intval($_POST["category_id"]);
  $img = upload_custom("image", "Items");


    $langs = get_restaurant_langs($restaurant_id);

    $fields = "restaurant_id, category_id, image, base_price, ordering, active";
    $values = "?, ?, ?, ?, ?, ?";
    $params = [
        $restaurant_id,
        $cat_id,
        $img,
        floatval($_POST['price']),
        9999,
        1
    ];

    foreach ($langs as $l) {
        $fields .= ", name_$l, description_$l";
        $values .= ", ?, ?";
        $params[] = $_POST["name_$l"] ?? "";
        $params[] = $_POST["description_$l"] ?? "";
    }

    db()->prepare("INSERT INTO items ($fields) VALUES ($values)")
       ->execute($params);

    header("Location: menu_builder.php");
    exit;


/* ---------- EDIT ITEM ---------- */
case "edit_item":

    $id = intval($_POST['id']);

    $old = fetch_one("
        SELECT image FROM items 
        WHERE id = ? AND restaurant_id = ?
    ", [$id, $restaurant_id]);

    $new_img = upload_custom("image", "Items", $old['image']);


    $langs = get_restaurant_langs($restaurant_id);

    $sql    = "UPDATE items SET image = ?, base_price = ?";
    $params = [$new_img, floatval($_POST['price'])];

    foreach ($langs as $l) {
        $sql .= ", name_$l = ?, description_$l = ?";
        $params[] = $_POST["name_$l"] ?? "";
        $params[] = $_POST["description_$l"] ?? "";
    }

    $sql .= " WHERE id = ? AND restaurant_id = ?";
    $params[] = $id;
    $params[] = $restaurant_id;

    db()->prepare($sql)->execute($params);

    header("Location: menu_builder.php");
    exit;


/* ---------- DELETE ITEM ---------- */
case "delete_item":

    $id = intval($_POST["id"]);

    db()->prepare("DELETE FROM items WHERE id = ? AND restaurant_id = ?")
       ->execute([$id, $restaurant_id]);

    echo "1";
    exit;


/* ---------- TOGGLE ITEM ---------- */
case "toggle_item":

    $id = intval($_POST["id"]);

    $current = fetch_value("
        SELECT active FROM items 
        WHERE id = ? AND restaurant_id = ?
    ", [$id, $restaurant_id]);

    $new = $current ? 0 : 1;

    db()->prepare("
        UPDATE items 
        SET active = ? 
        WHERE id = ? AND restaurant_id = ?
    ")->execute([$new, $id, $restaurant_id]);

    echo "1";
    exit;


/* ---------- UPLOAD EXCEL (REDIRECT ONLY) ---------- */
case "upload_excel":

    if (!isset($_FILES['excel']) || $_FILES['excel']['error'] !== 0) {
        die("خطأ في رفع الملف");
    }

    move_uploaded_file($_FILES['excel']['tmp_name'], "excel_upload.xlsx");
    header("Location: excel_import.php");
    exit;


/* ---------- GET OPTIONS ---------- */
case "get_options":

    $id = intval($_POST['id']);
    $rows = get_item_options($id);
    $data = [];

    foreach ($rows as $r) {
        $data[] = [
            "id"      => $r['id'],
            "name_ar" => $r['name_ar'],
            "name_en" => $r['name_en'],
            "name_ku" => $r['name_ku'],
            "price"   => $r['price'],
            "image"   => build_image_url_json($r['image'], 'Options')
        ];
    }

    echo json_encode($data);
    exit;


/* ---------- ADD OPTION ---------- */
case "add_option":

    $item_id = intval($_POST['item_id']);
   $img = upload_custom("image", "Options");


    $langs = get_restaurant_langs($restaurant_id);

    $fields = "item_id, image, price, ordering, active";
    $values = "?, ?, ?, 0, 1";
    $params = [$item_id, $img, floatval($_POST['price'])];

    foreach ($langs as $l) {
        $fields .= ", name_$l, description_$l";
        $values .= ", ?, ?";
        $params[] = $_POST["name_$l"] ?? "";
        $params[] = $_POST["description_$l"] ?? "";
    }

    db()->prepare("INSERT INTO item_options ($fields) VALUES ($values)")
       ->execute($params);

    header("Location: menu_builder.php");
    exit;


/* ---------- DELETE OPTION ---------- */
case "delete_option":

    delete_item_option($_POST['id']);
    exit;


/* ---------- INVALID REQUEST ---------- */
default:
    echo "Invalid Request";
    exit;
}
