<?php

require_once __DIR__ . "/db.php";
require_once __DIR__ . "/security.php";

/*
|--------------------------------------------------------------------------|
| DB SHORTCUT
|--------------------------------------------------------------------------|
*/
if (!function_exists("db")) {
    function db() {
        global $pdo;
        return $pdo;
    }
}

/*
|--------------------------------------------------------------------------|
| GENERIC HELPERS
|--------------------------------------------------------------------------|
*/
function fetch_all($sql, $params = []) {
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetchAll();
}

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

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

/*
|--------------------------------------------------------------------------|
| FILE HELPERS  (Delete only by filename)
|--------------------------------------------------------------------------|
*/
function delete_file($filename) {
    if (!$filename) return;
    $filename = basename($filename); // أمان + إزالة مسار إن وُجد
    $base = $_SERVER['DOCUMENT_ROOT'] . "/menu/uploads/";

    // بحث عن الملف في كل مجلدات الرفع
    $folders = ['Logo', 'Banners', 'MenuBG', 'Videos', 'Options', 'Social'];
    foreach($folders as $f) {
        $full = $base . $f . "/" . $filename;
        if (file_exists($full)) {
            @unlink($full);
        }
    }
}

/*
|--------------------------------------------------------------------------|
| RESTAURANT
|--------------------------------------------------------------------------|
*/
function get_restaurant($id) {
    return fetch_one("SELECT * FROM restaurants WHERE id = ?", [$id]);
}

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

/**
 * تعديل إعدادات المطعم + تخزين أسماء فقط بدون مسارات
 */
function update_restaurant_settings($id, $data)
{
    if (!$data || !is_array($data)) return false;

    unset($data['owner_id']); // لا نسمح بتحديثه نهائياً

    $fields = [];
    $values = [];

    foreach ($data as $key => $value) {
        $fields[] = "`$key` = ?";
        $values[] = $value;
    }

    $values[] = $id;

    $sql = "UPDATE restaurants SET " . implode(", ", $fields) . " WHERE id = ?";

    $stmt = db()->prepare($sql);
    return $stmt->execute($values);
}

/*
|--------------------------------------------------------------------------|
| BRANCHES
|--------------------------------------------------------------------------|
*/
function get_branches($restaurant_id) {
    return fetch_all(
        "SELECT * FROM branches WHERE restaurant_id = ? ORDER BY ordering ASC",
        [$restaurant_id]
    );
}

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

function update_branch($id, $data) {
    $sql = "UPDATE branches SET 
              name = ?, 
              name_ar = ?, 
              name_en = ?, 
              name_ku = ?, 
              description = ?, 
              address = ?, 
              phone = ?, 
              whatsapp = ?, 
              map_url = ?, 
              facebook = ?, 
              instagram = ?, 
              tiktok = ?, 
              youtube = ?, 
              cover_image = ?, 
              cover_video = ?,
              theme_color = ?, 
              theme_background = ?, 
              theme_text_color = ?, 
              card_style = ?, 
              menu_type = ?, 
              menu_mode = ?, 
              ordering = ?, 
              active = ?
            WHERE id = ?";

    db()->prepare($sql)->execute([
        $data['name'],
        $data['name_ar'],
        $data['name_en'],
        $data['name_ku'],
        $data['description'],
        $data['address'],
        $data['phone'],
        $data['whatsapp'],
        $data['map_url'],
        $data['facebook'],
        $data['instagram'],
        $data['tiktok'],
        $data['youtube'],
        $data['cover_image'],   // اسم فقط
        $data['cover_video'],   // اسم فقط
        $data['theme_color'],
        $data['theme_background'],
        $data['theme_text_color'],
        $data['card_style'],
        $data['menu_type'],
        $data['menu_mode'],
        $data['ordering'],
        $data['active'],
        $id
    ]);
}

/*
|--------------------------------------------------------------------------|
| CATEGORIES
|--------------------------------------------------------------------------|
*/
function get_categories($restaurant_id) {
    return fetch_all(
        "SELECT * FROM categories 
         WHERE restaurant_id = ? 
         ORDER BY ordering ASC",
        [$restaurant_id]
    );
}

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

function toggle_category($id, $active) {
    db()->prepare("UPDATE categories SET active = ? WHERE id = ?")
       ->execute([$active, $id]);
}

/*
|--------------------------------------------------------------------------|
| ITEMS
|--------------------------------------------------------------------------|
*/
function get_items($restaurant_id) {
    return fetch_all(
        "SELECT * FROM items 
         WHERE restaurant_id = ? 
         ORDER BY ordering ASC",
        [$restaurant_id]
    );
}

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

function toggle_item($id, $active) {
    db()->prepare("UPDATE items SET active = ? WHERE id = ?")
       ->execute([$active, $id]);
}

/*
|--------------------------------------------------------------------------|
| BRANCH ITEM PRICES
|--------------------------------------------------------------------------|
*/
function get_branch_item($branch_id, $item_id) {
    return fetch_one("
        SELECT * FROM branch_items 
        WHERE branch_id = ? AND item_id = ?
    ", [$branch_id, $item_id]);
}

function set_branch_item_price($branch_id, $item_id, $price) {
    $exists = fetch_value("
        SELECT id FROM branch_items 
        WHERE branch_id = ? AND item_id = ?
    ", [$branch_id, $item_id]);

    if ($exists) {
        db()->prepare("
            UPDATE branch_items SET price = ? 
            WHERE branch_id = ? AND item_id = ?
        ")->execute([$price, $branch_id, $item_id]);
    } else {
        db()->prepare("
            INSERT INTO branch_items (branch_id, item_id, price) 
            VALUES (?, ?, ?)
        ")->execute([$branch_id, $item_id, $price]);
    }
}

/*
|--------------------------------------------------------------------------|
| DISCOUNTS
|--------------------------------------------------------------------------|
*/
function get_discounts($restaurant_id) {
    return fetch_all(
        "SELECT * FROM discounts 
         WHERE restaurant_id = ? 
         ORDER BY start_date DESC",
        [$restaurant_id]
    );
}

function get_active_discount_for_item($restaurant_id, $branch_id, $item_id) {
    return fetch_one("
        SELECT * FROM discounts
         WHERE item_id = ?
           AND restaurant_id = ?
           AND active = 1
           AND (branch_id = ? OR branch_id IS NULL)
           AND NOW() BETWEEN start_date AND end_date
         ORDER BY branch_id DESC
         LIMIT 1
    ", [$item_id, $restaurant_id, $branch_id]);
}

/*
|--------------------------------------------------------------------------|
| BANNERS
|--------------------------------------------------------------------------|
*/
function get_banners($restaurant_id) {
    return fetch_all("
        SELECT * FROM banners 
        WHERE restaurant_id = ? 
        ORDER BY ordering ASC
    ", [$restaurant_id]);
}

/*
|--------------------------------------------------------------------------|
| BRANCH SOCIAL
|--------------------------------------------------------------------------|
*/
function get_branch_social($branch_id) {
    return fetch_all("
        SELECT * FROM branch_social 
        WHERE branch_id = ? AND active = 1 
        ORDER BY ordering ASC
    ", [$branch_id]);
}

function add_branch_social($branch_id, $icon, $url) {
    db()->prepare("
        INSERT INTO branch_social (branch_id, icon, url, ordering, active)
        VALUES (?, ?, ?, 0, 1)
    ")->execute([$branch_id, $icon, $url]);
}

/*
|--------------------------------------------------------------------------|
| LANGUAGES
|--------------------------------------------------------------------------|
*/
function get_enabled_languages($restaurant) {
    $rows = 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']]);

    if (!$rows) return ['ar'];
return array_column($rows, 'code');

}

/*
|--------------------------------------------------------------------------|
| LOGGING
|--------------------------------------------------------------------------|
*/
function log_action($manager_id, $action, $details = null) {
    $sql = "INSERT INTO logs (manager_id, action, details, ip, agent)
            VALUES (?, ?, ?, ?, ?)";

    db()->prepare($sql)->execute([
        $manager_id,
        $action,
        $details,
        $_SERVER['REMOTE_ADDR'] ?? '',
        $_SERVER['HTTP_USER_AGENT'] ?? ''
    ]);
}

/*
|--------------------------------------------------------------------------|
| GET AVAILABLE LANGUAGES FOR RESTAURANT
|--------------------------------------------------------------------------|
*/
function get_restaurant_languages($restaurant_id) {
    return 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]);
}

/*
|--------------------------------------------------------------------------|
| UPLOAD HELPERS  => تخزين أسماء فقط بدون مسارات
|--------------------------------------------------------------------------|
*/

/**
 * رفع صورة (اسم فقط)
 */
function upload_custom($input, $folder, $old = null) {

    if (!isset($_FILES[$input]) || $_FILES[$input]['error'] !== 0) {
        return $old;
    }

    // توحيد اسم المجلد
    $folderKey = strtolower($folder);

    $rules = [
        "banners"    => ["w"=>800,  "h"=>450],
        "categories" => ["w"=>1024, "h"=>1024],
        "logo"       => ["w"=>800,  "h"=>800],
        "options"    => ["w"=>920,  "h"=>920],
         "items"      => ["w"=>1200, "h"=>800],
        "menubg"     => ["w"=>1080, "h"=>1920],
        "videos"     => ["video"=>true],
    ];

    if (!isset($rules[$folderKey])) {
        $_SESSION['upload_error'] = "نوع الملف غير معروف";
        return $old;
    }

    $rule = $rules[$folderKey];
    $dir = $_SERVER['DOCUMENT_ROOT'] . "/menu/uploads/{$folder}/";
    if (!is_dir($dir)) mkdir($dir, 0777, true);

    $ext = strtolower(pathinfo($_FILES[$input]['name'], PATHINFO_EXTENSION));
    $maxBytes = 1024 * 1024; // 1MB

    /* ================= فيديو ================= */
  if (isset($rule['video'])) {

    $allowedVideo = ['mp4','webm','mov'];
    if (!in_array($ext, $allowedVideo)) {
        $_SESSION['upload_error'] = "صيغة فيديو غير مدعومة";
        return $old;
    }

    // حد أقصى للحجم (مثلاً 50MB)
    $maxVideoSize = 50 * 1024 * 1024;
    if ($_FILES[$input]['size'] > $maxVideoSize) {
        $_SESSION['upload_error'] = "حجم الفيديو أكبر من المسموح";
        return $old;
    }

    $newName = uniqid("v_") . "." . $ext;
    move_uploaded_file($_FILES[$input]['tmp_name'], $dir.$newName);

    delete_file($old);
    return $newName;
}


    /* ================= صورة ================= */
    $allowedImg = ['jpg','jpeg','png','webp'];
    if (!in_array($ext, $allowedImg)) {
        $_SESSION['upload_error'] = "صيغة صورة غير مدعومة";
        return $old;
    }

    $info = getimagesize($_FILES[$input]['tmp_name']);
    if (!$info) {
        $_SESSION['upload_error'] = "الملف ليس صورة";
        return $old;
    }

    switch ($info['mime']) {
        case 'image/jpeg': $src = imagecreatefromjpeg($_FILES[$input]['tmp_name']); break;
        case 'image/png':  $src = imagecreatefrompng($_FILES[$input]['tmp_name']);  break;
        case 'image/webp': $src = imagecreatefromwebp($_FILES[$input]['tmp_name']); break;
        default:
            $_SESSION['upload_error'] = "نوع صورة غير مدعوم";
            return $old;
    }

    $dstW = $rule['w'];
    $dstH = $rule['h'];
    $dst = imagecreatetruecolor($dstW, $dstH);

    imagealphablending($dst, false);
    imagesavealpha($dst, true);

    // قص مركزي
    $srcW = imagesx($src);
    $srcH = imagesy($src);
    $srcRatio = $srcW / $srcH;
    $dstRatio = $dstW / $dstH;

    if ($srcRatio > $dstRatio) {
        $newW = $srcH * $dstRatio;
        $x = ($srcW - $newW) / 2;
        imagecopyresampled($dst, $src, 0, 0, $x, 0, $dstW, $dstH, $newW, $srcH);
    } else {
        $newH = $srcW / $dstRatio;
        $y = ($srcH - $newH) / 2;
        imagecopyresampled($dst, $src, 0, 0, 0, $y, $dstW, $dstH, $srcW, $newH);
    }

    // فرض WEBP + ضغط ≤ 1MB
    $newName = uniqid("m_") . ".webp";
    $target = $dir.$newName;
    $tmp = $target.".tmp";

    $quality = 85;
    do {
        imagewebp($dst, $tmp, $quality);
        $size = filesize($tmp);
        $quality -= 5;
    } while ($size > $maxBytes && $quality >= 40);

    rename($tmp, $target);

    imagedestroy($src);
    imagedestroy($dst);

    delete_file($old);
    return $newName;
}

/*
|--------------------------------------------------------------------------|
| DELETE RESTAURANT ACCOUNT (Delete images by filename only)
|--------------------------------------------------------------------------|
*/
function delete_restaurant_account($restaurant_id, $manager_id) {

    // حذف صور المطعم نفسه
    $rest = get_restaurant($restaurant_id);
    if ($rest) {
        delete_file($rest['logo']);
        delete_file($rest['cover_image']);
        delete_file($rest['background_image']);
        delete_file($rest['background_video']);
    }

    // حذف منيو الفروع ثم الفروع
    db()->prepare("DELETE FROM branch_items WHERE branch_id IN (SELECT id FROM branches WHERE restaurant_id=?)")
        ->execute([$restaurant_id]);

    // حذف تواصل اجتماعي للفروع قبل حذف الفروع
    db()->prepare("DELETE FROM branch_social WHERE branch_id IN (SELECT id FROM branches WHERE restaurant_id=?)")
        ->execute([$restaurant_id]);

    db()->prepare("DELETE FROM branches WHERE restaurant_id=?")->execute([$restaurant_id]);

    // حذف أصناف وتصنيفات وبانرات وخصومات وزيارات
    db()->prepare("DELETE FROM items WHERE restaurant_id=?")->execute([$restaurant_id]);
    db()->prepare("DELETE FROM categories WHERE restaurant_id=?")->execute([$restaurant_id]);
    db()->prepare("DELETE FROM banners WHERE restaurant_id=?")->execute([$restaurant_id]);
    db()->prepare("DELETE FROM discounts WHERE restaurant_id=?")->execute([$restaurant_id]);
    db()->prepare("DELETE FROM visits WHERE restaurant_id=?")->execute([$restaurant_id]);

    // حذف المطعم والمدير
    db()->prepare("DELETE FROM restaurants WHERE id=?")->execute([$restaurant_id]);
    db()->prepare("DELETE FROM managers WHERE id=?")->execute([$manager_id]);
}

/*
|--------------------------------------------------------------------------|
| LIKES
|--------------------------------------------------------------------------|
*/
function get_item_likes($item_id, $branch_id){
    return fetch_value("SELECT COUNT(*) FROM item_likes WHERE item_id=? AND branch_id=?", [$item_id, $branch_id]);
}

function add_like($item_id, $branch_id){
    $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    $exists = fetch_value("SELECT id FROM item_likes WHERE item_id=? AND branch_id=? AND ip=?", [$item_id, $branch_id, $ip]);
    if (!$exists) {
        db()->prepare("INSERT INTO item_likes (item_id, branch_id, ip) VALUES (?,?,?)")
           ->execute([$item_id, $branch_id, $ip]);
    }
}

/*
|--------------------------------------------------------------------------|
| ITEM OPTIONS (CUSTOMIZATIONS)
|--------------------------------------------------------------------------|
*/
function get_item_options($item_id){
    return fetch_all("
        SELECT *, 
            image AS image_file,
            CONCAT('menu/uploads/Options/', image) AS image_url
        FROM item_options 
        WHERE item_id=? AND active=1
        ORDER BY ordering ASC
    ", [$item_id]);
}

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

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 upload_branch_file($input, $old = null) {
    if (!isset($_FILES[$input]) || $_FILES[$input]['error'] !== 0) {
        return $old;
    }

    $allowed = ['jpg','jpeg','png','webp','mp4','avi','mov'];
    $ext = strtolower(pathinfo($_FILES[$input]['name'], PATHINFO_EXTENSION));
    if(!in_array($ext,$allowed)) return $old;

    $new = uniqid("br_").".".$ext;
    $dir = $_SERVER['DOCUMENT_ROOT']."/menu/uploads/Branch/";
    if(!is_dir($dir)) mkdir($dir,0777,true);

    move_uploaded_file($_FILES[$input]['tmp_name'],$dir.$new);
    return $new;
}
/* ============================================
   CHECK PERMISSIONS
============================================ */
function check_permission($permission)
{
    if (!isset($_SESSION['manager_role'])) {
        return false;
    }

    $role = $_SESSION['manager_role'];

    // المدير (manager) له كل الصلاحيات
    if ($role === "manager") {
        return true;
    }

    // صلاحيات المحرر (editor)
    $editor_permissions = [
        "edit_menu",      // تعديل المنيو
        "edit_discounts", // إدارة الخصومات
        "edit_banners",   // إدارة البانرات
    ];

    return in_array($permission, $editor_permissions, true);
}
/* ============================================================
   MANAGERS FUNCTIONS
============================================================ */

/* جلب جميع المستخدمين */
function get_all_managers() {
    return fetch_all("
        SELECT id, name, email, role 
        FROM managers 
        ORDER BY id ASC
    ");
}

/* إضافة مستخدم جديد */
function add_manager($name, $email, $password, $role) {
    db()->prepare("
        INSERT INTO managers (name, email, password, role)
        VALUES (?, ?, ?, ?)
    ")->execute([$name, $email, $password, $role]);
}

/* تعديل بيانات مستخدم */
function update_manager($id, $name, $email, $role) {
    db()->prepare("
        UPDATE managers 
        SET name=?, email=?, role=? 
        WHERE id=?
    ")->execute([$name, $email, $role, $id]);
}

/* تعديل كلمة المرور */
function update_manager_password($id, $password) {
    db()->prepare("
        UPDATE managers 
        SET password=? 
        WHERE id=?
    ")->execute([$password, $id]);
}

/* حذف مستخدم */
function delete_manager($id) {
    db()->prepare("DELETE FROM managers WHERE id=?")->execute([$id]);
}
function get_restaurant_managers($restaurant_id) {
    return fetch_all("
        SELECT * FROM managers 
        WHERE restaurant_id = ?
    ", [$restaurant_id]);
}
