<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';

$auth = new Auth();
$auth->requireRole(['restaurant_admin', 'restaurant_manager']);

$csrf = new CSRF();
$restaurantId = $auth->restaurantId();
$userId = $auth->userId();
$db = Database::getInstance();
$baseUrl = getBaseUrl();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(false, 'Invalid request');
}

if (empty($_POST['csrf_token']) || !$csrf->verify($_POST['csrf_token'])) {
    jsonResponse(false, 'Invalid CSRF token');
}

$tab = $_POST['tab'] ?? 'general';
$existing = $db->query("SELECT id FROM restaurant_settings WHERE restaurant_id = ?", [$restaurantId])->fetch();

$updateData = [];

switch ($tab) {
    case 'general':
        $updateData = [
            'google_maps_link' => trim($_POST['google_maps_link'] ?? ''),
            'facebook_url' => trim($_POST['facebook_url'] ?? ''),
            'instagram_url' => trim($_POST['instagram_url'] ?? ''),
            'twitter_url' => trim($_POST['twitter_url'] ?? ''),
        ];
        break;

    case 'order':
        $updateData = [
            'min_order' => (float)($_POST['min_order'] ?? 0),
            'tax_percent' => (float)($_POST['tax_percent'] ?? 0),
            'service_charge_percent' => (float)($_POST['service_charge_percent'] ?? 0),
            'delivery_charge' => (float)($_POST['delivery_charge'] ?? 0),
            'prep_time_minutes' => (int)($_POST['prep_time_minutes'] ?? 15),
            'order_prefix' => trim($_POST['order_prefix'] ?? 'ORD'),
            'dine_in_enabled' => isset($_POST['dine_in_enabled']) ? 1 : 0,
            'takeaway_enabled' => isset($_POST['takeaway_enabled']) ? 1 : 0,
            'delivery_enabled' => isset($_POST['delivery_enabled']) ? 1 : 0,
            'order_acceptance' => isset($_POST['order_acceptance']) ? 1 : 0,
        ];
        $operatingMode = (int)($_POST['operating_mode'] ?? 1);
        $db->update('restaurants', ['operating_mode' => $operatingMode], 'id = ?', [$restaurantId]);
        break;

    case 'appearance':
        $updateData = [
            'primary_color' => trim($_POST['primary_color'] ?? '#E63946'),
            'secondary_color' => trim($_POST['secondary_color'] ?? '#1D3557'),
            'font_preference' => $_POST['font_preference'] ?? 'Poppins',
            'menu_layout' => $_POST['menu_layout'] ?? 'grid',
            'item_card_style' => $_POST['item_card_style'] ?? 'classic',
        ];
        break;

    case 'hours':
        $hours = $_POST['hours'] ?? [];
        $openingHours = [];
        $days = ['monday','tuesday','wednesday','thursday','friday','saturday','sunday'];
        foreach ($days as $day) {
            $open = trim($hours[$day . '_open'] ?? '');
            $close = trim($hours[$day . '_close'] ?? '');
            $openingHours[$day . '_open'] = $open;
            $openingHours[$day . '_close'] = $close;
        }
        $updateData = [
            'opening_hours' => json_encode($openingHours),
        ];
        break;

    case 'payment':
        $updateData = [
            'payment_cash' => isset($_POST['payment_cash']) ? 1 : 0,
            'payment_card' => isset($_POST['payment_card']) ? 1 : 0,
            'payment_online' => isset($_POST['payment_online']) ? 1 : 0,
            'payment_bank_transfer' => isset($_POST['payment_bank_transfer']) ? 1 : 0,
        ];
        break;

    case 'notifications':
        $updateData = [
            'sound_notification' => isset($_POST['sound_notification']) ? 1 : 0,
            'refresh_interval' => max(10, min(300, (int)($_POST['refresh_interval'] ?? 30))),
        ];
        break;

    case 'wifi':
        $updateData = [
            'wifi_name' => trim($_POST['wifi_name'] ?? ''),
            'wifi_password' => trim($_POST['wifi_password'] ?? ''),
        ];
        break;

    case 'terms':
        $updateData = [
            'terms' => trim($_POST['terms'] ?? ''),
            'allergy_notice' => trim($_POST['allergy_notice'] ?? ''),
            'customer_notice' => trim($_POST['customer_notice'] ?? ''),
            'footer_message' => trim($_POST['footer_message'] ?? ''),
        ];
        break;
}

if (!empty($updateData)) {
    if ($existing) {
        $db->update('restaurant_settings', $updateData, 'restaurant_id = ?', [$restaurantId]);
    } else {
        $updateData['restaurant_id'] = $restaurantId;
        $db->insert('restaurant_settings', $updateData);
    }
}

$activityLog = new ActivityLog();
$activityLog->log($userId, $restaurantId, 'settings', 'update', ucfirst($tab) . ' settings updated');

jsonResponse(true, ucfirst($tab) . ' settings saved successfully', ['redirect' => $baseUrl . '/restaurant-admin/settings.php?tab=' . $tab]);
