<?php
session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';
header('Content-Type: application/json; charset=utf-8');

$auth = new Auth();
if (!$auth->check() || !$auth->isSuperAdmin()) { jsonResponse(false, 'Unauthorized', [], 401); }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { jsonResponse(false, 'Invalid method.'); }

$csrf = new CSRF();
if (!$csrf->verify($_POST['csrf_token'] ?? '')) { jsonResponse(false, 'Invalid CSRF token.'); }

$password = $_POST['password'] ?? '';
if (empty($password)) { jsonResponse(false, 'Password is required.'); }

$user = $auth->user();
$db = Database::getInstance();
$stmt = $db->query("SELECT password FROM users WHERE id = ?", [$user['id']]);
$dbUser = $stmt->fetch();

if (!$dbUser || !password_verify($password, $dbUser['password'])) {
    jsonResponse(false, 'Incorrect admin password.');
}

try {
    $db->beginTransaction();

    $demoRestaurantIds = [];
    $stmt = $db->query("SELECT id FROM restaurants WHERE is_demo = 1");
    while ($row = $stmt->fetch()) {
        $demoRestaurantIds[] = (int) $row['id'];
    }

    if (!empty($demoRestaurantIds)) {
        $placeholders = implode(',', array_fill(0, count($demoRestaurantIds), '?'));
        $params = $demoRestaurantIds;

        $db->query("DELETE FROM order_item_addons WHERE order_item_id IN (SELECT id FROM order_items WHERE order_id IN (SELECT id FROM orders WHERE restaurant_id IN ({$placeholders})))", $params);
        $db->query("DELETE FROM order_items WHERE order_id IN (SELECT id FROM orders WHERE restaurant_id IN ({$placeholders}))", $params);
        $db->query("DELETE FROM order_status_history WHERE order_id IN (SELECT id FROM orders WHERE restaurant_id IN ({$placeholders}))", $params);
        $db->query("DELETE FROM orders WHERE restaurant_id IN ({$placeholders})", $params);
        $db->query("DELETE FROM payments WHERE restaurant_id IN ({$placeholders})", $params);
        $db->query("DELETE FROM qr_scan_logs WHERE restaurant_id IN ({$placeholders})", $params);
        $db->query("DELETE FROM menu_view_logs WHERE restaurant_id IN ({$placeholders})", $params);
        $db->query("DELETE FROM addons WHERE restaurant_id IN ({$placeholders})", $params);
        $db->query("DELETE FROM addon_groups WHERE restaurant_id IN ({$placeholders})", $params);
        $db->query("DELETE FROM item_variations WHERE restaurant_id IN ({$placeholders})", $params);
        $db->query("DELETE FROM advertisements WHERE restaurant_id IN ({$placeholders})", $params);
        $db->query("DELETE FROM offers WHERE restaurant_id IN ({$placeholders})", $params);
        $db->query("DELETE FROM menu_items WHERE restaurant_id IN ({$placeholders})", $params);
        $db->query("DELETE FROM categories WHERE restaurant_id IN ({$placeholders})", $params);
        $db->query("DELETE FROM tables WHERE restaurant_id IN ({$placeholders})", $params);
        $db->query("DELETE FROM qr_codes WHERE restaurant_id IN ({$placeholders})", $params);
        $db->query("DELETE FROM customers WHERE restaurant_id IN ({$placeholders})", $params);
        $db->query("DELETE FROM notifications WHERE restaurant_id IN ({$placeholders})", $params);
        $db->query("DELETE FROM activity_logs WHERE restaurant_id IN ({$placeholders})", $params);
        $db->query("DELETE FROM restaurant_settings WHERE restaurant_id IN ({$placeholders})", $params);
        $db->query("DELETE FROM users WHERE restaurant_id IN ({$placeholders})", $params);
        $db->query("DELETE FROM restaurants WHERE is_demo = 1");
    }

    $activityLog = new ActivityLog();
    $activityLog->log($_SESSION['user_id'], null, 'demo', 'remove', 'Removed all demo data');

    $db->commit();
    jsonResponse(true, 'All demo data has been removed successfully.');

} catch (Exception $e) {
    $db->rollback();
    error_log('Demo remove error: ' . $e->getMessage());
    jsonResponse(false, 'Error removing demo data: ' . $e->getMessage());
}
