<?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', 'cashier', 'kitchen_staff', 'waiter']);

$restaurantId = $auth->restaurantId();
$userId = $auth->userId();

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

if (empty($_POST['csrf_token'])) {
    jsonResponse(false, 'CSRF token required');
}

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

$action = $_POST['action'] ?? '';

if ($action !== 'update_profile') {
    jsonResponse(false, 'Invalid action');
}

$db = Database::getInstance();
$name = trim($_POST['name'] ?? '');
$slug = trim($_POST['slug'] ?? slugify($name));
$description = trim($_POST['description'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$whatsapp = trim($_POST['whatsapp'] ?? '');
$email = trim($_POST['email'] ?? '');
$address = trim($_POST['address'] ?? '');
$city = trim($_POST['city'] ?? '');
$country = trim($_POST['country'] ?? '');
$currency = $_POST['currency'] ?? 'USD';
$timezone = $_POST['timezone'] ?? 'UTC';

if (empty($name)) {
    jsonResponse(false, 'Restaurant name is required');
}

$logo = null;
$coverImage = null;
$upload = new Upload();

if (!empty($_FILES['logo']['name'])) {
    $result = $upload->uploadFile($_FILES['logo'], 'restaurants/' . $restaurantId);
    if ($result['success']) {
        $logo = $result['path'];
    } else {
        jsonResponse(false, 'Logo upload failed: ' . implode(', ', $result['errors']));
    }
}

if (!empty($_FILES['cover_image']['name'])) {
    $result = $upload->uploadFile($_FILES['cover_image'], 'restaurants/' . $restaurantId);
    if ($result['success']) {
        $coverImage = $result['path'];
    } else {
        jsonResponse(false, 'Cover image upload failed: ' . implode(', ', $result['errors']));
    }
}

$updateData = [
    'name' => $name,
    'slug' => $slug,
    'description' => $description,
    'phone' => $phone,
    'whatsapp' => $whatsapp,
    'email' => $email,
    'address' => $address,
    'city' => $city,
    'country' => $country,
    'currency' => $currency,
    'timezone' => $timezone,
];

if ($logo) {
    $updateData['logo'] = $logo;
}
if ($coverImage) {
    $updateData['cover_image'] = $coverImage;
}

$db->update('restaurants', $updateData, 'id = ?', [$restaurantId]);

$googleMapsLink = trim($_POST['google_maps_link'] ?? '');
$facebookUrl = trim($_POST['facebook_url'] ?? '');
$instagramUrl = trim($_POST['instagram_url'] ?? '');
$twitterUrl = trim($_POST['twitter_url'] ?? '');

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

if ($existing) {
    $db->update('restaurant_settings', [
        'google_maps_link' => $googleMapsLink,
        'facebook_url' => $facebookUrl,
        'instagram_url' => $instagramUrl,
        'twitter_url' => $twitterUrl,
    ], 'restaurant_id = ?', [$restaurantId]);
} else {
    $db->insert('restaurant_settings', [
        'restaurant_id' => $restaurantId,
        'google_maps_link' => $googleMapsLink,
        'facebook_url' => $facebookUrl,
        'instagram_url' => $instagramUrl,
        'twitter_url' => $twitterUrl,
    ]);
}

$activityLog = new ActivityLog();
$activityLog->log($userId, $restaurantId, 'restaurant', 'profile_update', 'Restaurant profile updated');

jsonResponse(true, 'Profile updated successfully', ['redirect' => getBaseUrl() . '/restaurant-admin/profile.php']);
