<?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 request method.');
}

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

$action = $_POST['action'] ?? '';
$id = (int) ($_POST['id'] ?? 0);

if ($id <= 0) {
    jsonResponse(false, 'Invalid restaurant ID.');
}

$db = Database::getInstance();
$restaurant = $db->query("SELECT * FROM restaurants WHERE id = ?", [$id])->fetch();

if (!$restaurant) {
    jsonResponse(false, 'Restaurant not found.');
}

switch ($action) {
    case 'toggle_status':
        $newStatus = ($restaurant['status'] === 'active' || $restaurant['status'] === 'trial') ? 'suspended' : 'active';
        $db->update('restaurants', ['status' => $newStatus, 'updated_at' => date('Y-m-d H:i:s')], 'id = ?', [$id]);

        $activityLog = new ActivityLog();
        $activityLog->log(
            $_SESSION['user_id'],
            $id,
            'restaurant',
            'status_toggle',
            'Changed status from ' . $restaurant['status'] . ' to ' . $newStatus . ' for: ' . $restaurant['name'],
            $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1'
        );

        jsonResponse(true, 'Restaurant status changed to ' . ucfirst($newStatus));
        break;

    case 'delete':
        $db->update('restaurants', ['is_active' => 0, 'status' => 'cancelled', 'updated_at' => date('Y-m-d H:i:s')], 'id = ?', [$id]);

        $activityLog = new ActivityLog();
        $activityLog->log(
            $_SESSION['user_id'],
            $id,
            'restaurant',
            'delete',
            'Soft deleted restaurant: ' . $restaurant['name'],
            $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1'
        );

        jsonResponse(true, 'Restaurant deleted successfully.');
        break;

    case 'reset_password':
        $newPassword = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 12);
        $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);

        $adminUser = $db->query("SELECT id FROM users WHERE restaurant_id = ? AND role_id = 2 LIMIT 1", [$id])->fetch();
        if ($adminUser) {
            $db->update('users', ['password' => $hashedPassword, 'updated_at' => date('Y-m-d H:i:s')], 'id = ?', [$adminUser['id']]);

            $activityLog = new ActivityLog();
            $activityLog->log(
                $_SESSION['user_id'],
                $id,
                'restaurant',
                'password_reset',
                'Reset admin password for restaurant: ' . $restaurant['name'],
                $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1'
            );

            jsonResponse(true, 'Password reset successfully. New password: ' . $newPassword, ['new_password' => $newPassword]);
        } else {
            jsonResponse(false, 'No admin account found for this restaurant.');
        }
        break;

    default:
        jsonResponse(false, 'Invalid action.');
}
