<?php
// super_admin/includes/functions.php

require_once __DIR__ . "/db.php";

/*
|--------------------------------------------------------------------------
| 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();
}

function clean($s) {
    return htmlspecialchars(trim($s), ENT_QUOTES, 'UTF-8');
}

/*
|--------------------------------------------------------------------------
| RESTAURANTS
|--------------------------------------------------------------------------
*/
function get_restaurants() {
    return fetch_all("
        SELECT *
        FROM restaurants
        ORDER BY id DESC
    ");
}

function get_restaurant($id) {
    return fetch_one("
        SELECT *
        FROM restaurants
        WHERE id = ?
        LIMIT 1
    ", [$id]);
}

function get_branches_count($rest_id) {
    return fetch_value("
        SELECT COUNT(*)
        FROM branches
        WHERE restaurant_id = ?
    ", [$rest_id]);
}

function get_visits_count($rest_id) {
    return fetch_value("
        SELECT COUNT(*)
        FROM visits
        WHERE restaurant_id = ?
    ", [$rest_id]);
}

/*
|--------------------------------------------------------------------------
| GLOBAL VISITS (Dashboard)
|--------------------------------------------------------------------------
*/
function total_visits_all() {
    return fetch_value("SELECT COUNT(*) FROM visits");
}

function total_visits_today() {
    return fetch_value("
        SELECT COUNT(*)
        FROM visits
        WHERE DATE(created_at) = CURDATE()
    ");
}

/*
|--------------------------------------------------------------------------
| SUBSCRIPTION DATE CALCULATIONS
|--------------------------------------------------------------------------
*/
function subscription_days_left($end_date)
{
    if (!$end_date) return -999;

    $now = new DateTime();
    $end = new DateTime($end_date);

    // لما ينتهي الاشتراك بالكامل يرجع بالسالب
    $diff = $now->diff($end);

    return ($now <= $end) ? $diff->days : -$diff->days;
}

function subscription_color($days)
{
    if ($days > 20) return "green";
    if ($days >= 10) return "yellow";
    return "red"; // أقل من 10 أيام
}

/*
|--------------------------------------------------------------------------
| CREATE RESTAURANT FOLDER FROM /menu/Demo
|--------------------------------------------------------------------------
*/
function create_restaurant_folder($folder_name)
{
    $source = realpath(__DIR__ . "/../../Demo");
    $dest   = realpath(__DIR__ . "/../../") . "/$folder_name";

    if (!$source) {
        die("❌ Demo folder not found!");
    }

    if (!file_exists($dest)) {
        mkdir($dest, 0777, true);
    }

    copy_folder($source, $dest);
}

function copy_folder($src, $dst)
{
    if (!file_exists($dst)) {
        mkdir($dst, 0777, true);
    }

    $dir = opendir($src);

    while(false !== ($file = readdir($dir))) {
        if ($file == '.' || $file == '..') continue;

        if (is_dir("$src/$file")) {
            copy_folder("$src/$file", "$dst/$file");
        } else {
            copy("$src/$file", "$dst/$file");
        }
    }

    closedir($dir);
}

/*
|--------------------------------------------------------------------------
| QR GENERATION (REAL 10000px IMAGE)
|--------------------------------------------------------------------------
*/
function generate_qr($url, $path)
{
    include_once __DIR__ . "/qrlib.php";

    // QR افتراضي 1024px ثم نكبره إلى 10000px
    $temp = $path . "_tmp.png";

    QRcode::png($url, $temp, QR_ECLEVEL_H, 20, 1);

    // تكبير إلى 10000px
    $src = imagecreatefrompng($temp);
    $dst = imagecreatetruecolor(10000, 10000);

    imagecopyresampled($dst, $src, 0, 0, 0, 0, 10000, 10000, imagesx($src), imagesy($src));

    imagepng($dst, $path);

    unlink($temp);
}


function get_restaurant_languages($rest_id)
{
    return fetch_all("
        SELECT l.code, l.name 
        FROM restaurant_languages rl
        INNER JOIN languages l ON rl.language_id = l.id
        WHERE rl.restaurant_id = ? AND rl.active = 1
        ORDER BY l.id ASC
    ", [$rest_id]);
}




function get_restaurant_status($id){
    return fetch_value("SELECT active FROM restaurants WHERE id = ?", [$id]);
}
