<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . "/includes/auth.php";
ensure_super_admin();

require_once __DIR__ . "/includes/functions.php";

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die("Invalid request");
}

$id = (int)($_POST['id'] ?? 0);
if ($id <= 0) die("Invalid ID");

// جلب المطعم (لازم folder_name)
$restaurant = fetch_one("SELECT id, name, folder_name FROM restaurants WHERE id=?", [$id]);
if (!$restaurant) die("Restaurant not found");

$folder_name = (string)($restaurant['folder_name'] ?? '');
$folder_name = trim($folder_name);

// حماية من أي تلاعب بالمسار
if ($folder_name !== '' && !preg_match('/^[a-z0-9][a-z0-9\-]*$/i', $folder_name)) {
    die("Invalid folder_name");
}

/* =========================
   DELETE ONLY RESTAURANT FRONT FOLDER
   (NO uploads deletion)
========================= */
function rrmdir_safe($dir, $base_dir){
    if (!$dir || !is_dir($dir)) return true;

    $realBase = realpath($base_dir);
    $realDir  = realpath($dir);

    // لازم يكون داخل مجلد /menu فقط
    if (!$realBase || !$realDir) return false;
    if (strpos($realDir, $realBase) !== 0) return false;

    $it = new RecursiveDirectoryIterator($realDir, RecursiveDirectoryIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);

    foreach ($files as $file) {
        if ($file->isDir()) {
            @rmdir($file->getRealPath());
        } else {
            @unlink($file->getRealPath());
        }
    }
    return @rmdir($realDir);
}

$menu_base = realpath(__DIR__ . "/.."); // /menu
$folder_path = ($folder_name !== '' && $menu_base) ? ($menu_base . DIRECTORY_SEPARATOR . $folder_name) : null;

$folder_deleted = true;
if ($folder_path && is_dir($folder_path)) {
    $folder_deleted = rrmdir_safe($folder_path, $menu_base);
}

/* =========================
   DELETE DB ROWS (ALL RELATED TO restaurant_id)
========================= */
try {
    db()->beginTransaction();

    // 1) Reservations items (depends on reservations)
    db()->prepare("
        DELETE FROM reservation_items
        WHERE reservation_id IN (
            SELECT id FROM reservations WHERE restaurant_id = ?
        )
    ")->execute([$id]);

    // 2) Reservations + settings
    db()->prepare("DELETE FROM reservations WHERE restaurant_id=?")->execute([$id]);
    db()->prepare("DELETE FROM reservation_settings WHERE restaurant_id=?")->execute([$id]);

    // 3) Likes / options / branch_items that depend on items/branches
    db()->prepare("
        DELETE FROM item_options
        WHERE item_id IN (SELECT id FROM items WHERE restaurant_id=?)
    ")->execute([$id]);

    db()->prepare("
        DELETE FROM item_likes
        WHERE item_id IN (SELECT id FROM items WHERE restaurant_id=?)
           OR branch_id IN (SELECT id FROM branches WHERE restaurant_id=?)
    ")->execute([$id, $id]);

    db()->prepare("
        DELETE FROM branch_items
        WHERE branch_id IN (SELECT id FROM branches WHERE restaurant_id=?)
           OR item_id IN (SELECT id FROM items WHERE restaurant_id=?)
    ")->execute([$id, $id]);

    // 4) Social + QR + ratings + visits
    db()->prepare("
        DELETE FROM branch_social
        WHERE branch_id IN (SELECT id FROM branches WHERE restaurant_id=?)
    ")->execute([$id]);

    db()->prepare("DELETE FROM restaurant_social WHERE restaurant_id=?")->execute([$id]);
    db()->prepare("DELETE FROM qrcodes WHERE restaurant_id=?")->execute([$id]);
    db()->prepare("DELETE FROM ratings WHERE restaurant_id=?")->execute([$id]);
    db()->prepare("DELETE FROM visits WHERE restaurant_id=?")->execute([$id]);

    // 5) Menu data
    db()->prepare("DELETE FROM banners WHERE restaurant_id=?")->execute([$id]);
    db()->prepare("DELETE FROM discounts WHERE restaurant_id=?")->execute([$id]);
    db()->prepare("DELETE FROM categories WHERE restaurant_id=?")->execute([$id]);
    db()->prepare("DELETE FROM items WHERE restaurant_id=?")->execute([$id]);
    db()->prepare("DELETE FROM branches WHERE restaurant_id=?")->execute([$id]);

    // 6) Links / managers
    db()->prepare("DELETE FROM restaurant_languages WHERE restaurant_id=?")->execute([$id]);
    db()->prepare("DELETE FROM restaurant_users WHERE restaurant_id=?")->execute([$id]);
    db()->prepare("DELETE FROM managers WHERE restaurant_id=?")->execute([$id]);

    // 7) Finally restaurant row
    db()->prepare("DELETE FROM restaurants WHERE id=?")->execute([$id]);

    db()->commit();

} catch (Exception $e) {
    db()->rollBack();
    die("DB delete error: " . $e->getMessage());
}

// رجوع للصفحة مع حالة حذف المجلد
header("Location: restaurants.php?deleted=1&folder_deleted=" . ($folder_deleted ? "1" : "0"));
exit;
