<?php

// ======================================================
// SYSTEM LOADING + ERRORS
// ======================================================
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
date_default_timezone_set("Asia/Baghdad");

require_once __DIR__ . "/db.php";
// =======================
// DB SHORTCUT + FETCHERS
// =======================
if (!function_exists("db")) {
    function db() {
        global $pdo;
        return $pdo;
    }
}

function fetch_all($sql, $params = []) {
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function fetch_one($sql, $params = []) {
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

function fetch_value($sql, $params = []) {
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetchColumn();
}


// =======================
// GET RESTAURANT BY FOLDER
// =======================
function get_restaurant_by_folder($folder) {
    return fetch_one("SELECT * FROM restaurants WHERE folder_name = ?", [$folder]);
}

// ======================================================
// HELPER — safe fetch
// ======================================================
function db()
{
    global $pdo;
    return $pdo;
}

function url_path($path)
{
    return "../" . ltrim($path, "/");
}


// ======================================================
/// ======================================================
// GET RESTAURANT DATA (SAFE VERSION)
// ======================================================
function get_restaurant($folder_name)
{
    $sql = "SELECT * FROM restaurants WHERE folder_name = ? LIMIT 1";
    $stmt = db()->prepare($sql);
    $stmt->execute([$folder_name]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) return null;

    // تأكيد وجود social_mode حتى لو كان العمود خطأ أو NULL
    if (!isset($row['social_mode']) || empty($row['social_mode'])) {
        $row['social_mode'] = "same";
    }

    return $row;
}



// ======================================================
// GET BRANCH DATA
// ======================================================
function get_branch($branch_id)
{
    $sql = "SELECT * FROM branches WHERE id = ? LIMIT 1";
    $stmt = db()->prepare($sql);
    $stmt->execute([$branch_id]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}



// ======================================================
// GET BANNERS
// ======================================================
function get_banners($restaurant_id)
{
    $sql = "SELECT id, image, title, ordering 
            FROM banners 
            WHERE restaurant_id = ? AND active = 1 
            ORDER BY ordering ASC";

    $stmt = db()->prepare($sql);
    $stmt->execute([$restaurant_id]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}



// ======================================================
// GET CATEGORIES
// ======================================================
function get_categories($restaurant_id)
{
    $sql = "SELECT id, name, name_ar, name_en, name_ku, image, ordering
            FROM categories
            WHERE restaurant_id = ? AND active = 1
            ORDER BY ordering ASC";

    $stmt = db()->prepare($sql);
    $stmt->execute([$restaurant_id]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}



// ======================================================
// GET ACTIVE DISCOUNT
// ======================================================
function get_item_discount($restaurant_id, $branch_id, $item_id)
{
    $sql = "SELECT *
            FROM discounts
            WHERE restaurant_id = ?
              AND item_id = ?
              AND (branch_id = ? OR branch_id IS NULL)
              AND active = 1
              AND DATE(start_date) <= CURDATE()
              AND DATE(end_date) >= CURDATE()
            ORDER BY id DESC LIMIT 1";

    $stmt = db()->prepare($sql);
    $stmt->execute([$restaurant_id, $item_id, $branch_id]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}


// ======================================================
// GET ITEM FINAL PRICE WITH BRANCH + DISCOUNT
// ======================================================
function calculate_item_price($item, $branch_id, $restaurant_id)
{
    $item_id = $item['id'];
    $base_price = $item['base_price'];

    // 1) هل يوجد سعر خاص لهذا الفرع؟
    $sql = "SELECT price 
            FROM branch_items
            WHERE branch_id = ? AND item_id = ? AND active = 1
            LIMIT 1";

    $stmt = db()->prepare($sql);
    $stmt->execute([$branch_id, $item_id]);
    $branch_price = $stmt->fetchColumn();

    // إذا لا يوجد سعر فرع → استخدم السعر الأساسي
    $final_price = $branch_price !== false ? $branch_price : $base_price;
    $old_price = null;

    // 2) هل يوجد خصم فعّال؟
    $discount = get_item_discount($restaurant_id, $branch_id, $item_id);

    if ($discount) {
        $old_price = $final_price; // السعر قبل الخصم

        if ($discount['discount_type'] === "percent") {
            $final_price = $final_price - ($final_price * ($discount['discount_value'] / 100));
        } else {
            $final_price = max(0, $final_price - $discount['discount_value']);
        }

        $final_price = round($final_price, 2);
    }

    return [
        "price" => $final_price,
        "old_price" => $old_price
    ];
}




// ======================================================
// GET ITEMS OF CATEGORY
// ======================================================
function get_items_by_category($category_id, $branch_id, $restaurant_id)
{
    $sql = "SELECT DISTINCT i.*
            FROM items i
            WHERE i.category_id = ?
              AND i.restaurant_id = ?
              AND i.active = 1
            ORDER BY i.ordering ASC";

    $stmt = db()->prepare($sql);
    $stmt->execute([$category_id, $restaurant_id]);
    $items = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // حساب السعر النهائي
    foreach ($items as &$item) {
        $p = calculate_item_price($item, $branch_id, $restaurant_id);
        $item['final_price'] = $p['price'];
        $item['old_price']   = $p['old_price'];
    }

    return $items;
}



// ======================================================
// GET SINGLE ITEM DETAILS
// ======================================================
function get_item_details($item_id, $branch_id, $restaurant_id)
{
    $sql = "SELECT *
            FROM items
            WHERE id = ? AND restaurant_id = ? AND active = 1
            LIMIT 1";

    $stmt = db()->prepare($sql);
    $stmt->execute([$item_id, $restaurant_id]);
    $item = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$item) return null;

    $price = calculate_item_price($item, $branch_id, $restaurant_id);

    $item['final_price'] = $price['price'];
    $item['old_price']   = $price['old_price'];

    return $item;
}



// ======================================================
// TRACK VISITS
// ======================================================
function log_visit($branch_id, $restaurant_id, $page, $item_id = null, $category_id = null)
{
    $sql = "INSERT INTO visits (branch_id, restaurant_id, page, item_id, category_id, ip, user_agent)
            VALUES (?, ?, ?, ?, ?, ?, ?)";

    $stmt = db()->prepare($sql);
    $stmt->execute([
        $branch_id,
        $restaurant_id,
        $page,
        $item_id,
        $category_id,
        $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0',
        $_SERVER['HTTP_USER_AGENT'] ?? ''
    ]);
}



// ======================================================
// LANGUAGE SYSTEM
// ======================================================
function t($row, $field, $lang)
{
    $key = $field . "_" . $lang;

    if (!empty($row[$key])) return $row[$key];
    if (!empty($row[$field])) return $row[$field];

    return "";
}

// ======================================================
// GET ITEM LIKE COUNT
// ======================================================
function get_item_likes($item_id, $branch_id)
{
    $sql = "SELECT COUNT(*) 
            FROM item_likes 
            WHERE item_id = ? AND branch_id = ?";
    $stmt = db()->prepare($sql);
    $stmt->execute([$item_id, $branch_id]);
    return (int)$stmt->fetchColumn();
}


// ======================================================
// TOGGLE LIKE (ADD/REMOVE BY IP)
// ======================================================
function toggle_like($item_id, $branch_id)
{
    $ip = $_SERVER['REMOTE_ADDR'] ?? "0.0.0.0";

    $check = db()->prepare("
        SELECT id FROM item_likes 
        WHERE item_id = ? AND branch_id = ? AND ip = ?
    ");
    $check->execute([$item_id, $branch_id, $ip]);
    $exists = $check->fetchColumn();

    if ($exists) {
        // إزالة اللايك
        $del = db()->prepare("DELETE FROM item_likes WHERE id = ?");
        $del->execute([$exists]);
    } else {
        // إضافة لايك
        $ins = db()->prepare("
            INSERT INTO item_likes (item_id, branch_id, ip) 
            VALUES (?, ?, ?)
        ");
        $ins->execute([$item_id, $branch_id, $ip]);
    }

    // إعادة العدد الجديد
    $count = get_item_likes($item_id, $branch_id);
    return $count;
}
/* -------------------------------------------------
| ITEM OPTIONS (CUSTOMIZATIONS)
--------------------------------------------------*/

function get_item_options($item_id){
    return fetch_all("
        SELECT * FROM item_options 
        WHERE item_id = ? 
        AND active = 1
        ORDER BY ordering ASC
    ", [$item_id]);
}

function get_item_option($id){
    return fetch_one("SELECT * FROM item_options WHERE id = ?", [$id]);
}

function add_item_option($item_id, $name_ar, $name_en, $name_ku, $price, $image){
    db()->prepare("
        INSERT INTO item_options (item_id, name_ar, name_en, name_ku, price, image, ordering, active)
        VALUES (?,?,?,?,?,?,0,1)
    ")->execute([
        $item_id, $name_ar, $name_en, $name_ku, $price, $image
    ]);
}

function update_item_option($id, $name_ar, $name_en, $name_ku, $price, $image = null){
    if($image){
        db()->prepare("
            UPDATE item_options SET name_ar=?, name_en=?, name_ku=?, price=?, image=? 
            WHERE id=?
        ")->execute([$name_ar,$name_en,$name_ku,$price,$image,$id]);
    } else {
        db()->prepare("
            UPDATE item_options SET name_ar=?, name_en=?, name_ku=?, price=? 
            WHERE id=?
        ")->execute([$name_ar,$name_en,$name_ku,$price,$id]);
    }
}

function delete_item_option($id){
    db()->prepare("DELETE FROM item_options WHERE id=?")->execute([$id]);
}
function icon_to_cdn($icon){
    if(!$icon) return "unknown";

    // خريطة تطابق إضافية لو أراد تعديل اسم
    $map = [
        "fa-whatsapp" => "whatsapp",
        "fa-tiktok" => "tiktok",
        "fa-facebook" => "facebook",
        "fa-instagram" => "instagram",
        "fa-youtube" => "youtube",
        "fa-twitter" => "twitter",
        "fa-x-twitter" => "twitter",
    ];

    // تقسيم الكلاس
    $parts = explode(" ", strtolower(trim($icon)));

    foreach($parts as $p){
        if(substr($p, 0, 3) === "fa-"){
            // تطابق مع خريطة التحويل
            if(isset($map[$p])) return $map[$p];
            // بدون map → إرجاع الاسم من غير fa-
            return str_replace("fa-", "", $p);
        }
    }

    // fallback
    return preg_replace("/[^a-z0-9]/", "", strtolower($icon));
}
/* ==========================================
   CHECK IF USER ALREADY LIKED ITEM (RETURN BOOLEAN)
=========================================== */
function user_liked_item($item_id, $branch_id){
    $ip = $_SERVER['REMOTE_ADDR']; // IP الزائر

    return fetch_value(
        "SELECT COUNT(*) FROM item_likes WHERE item_id=? AND branch_id=? AND ip=?",
        [$item_id, $branch_id, $ip]
    ) > 0;
}
