<?php
session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';

$auth = new Auth();
if (!$auth->check() || !$auth->isSuperAdmin()) {
    redirect('/login.php');
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect('/admin/restaurants.php');
}

$csrf = new CSRF();
if (!$csrf->verify($_POST['csrf_token'] ?? '')) {
    $_SESSION['flash_error'] = 'Invalid CSRF token.';
    redirect('/admin/restaurant_' . ($_POST['action'] ?? 'add') . '.php');
}

$db = Database::getInstance();
$action = $_POST['action'] ?? 'add';
$id = (int) ($_POST['id'] ?? 0);

$name = trim($_POST['name'] ?? '');
$slug = trim($_POST['slug'] ?? slugify($name));
$code = trim($_POST['code'] ?? generateCode(6));
$ownerName = trim($_POST['owner_name'] ?? '');
$email = trim($_POST['email'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$whatsapp = trim($_POST['whatsapp'] ?? '');
$address = trim($_POST['address'] ?? '');
$city = trim($_POST['city'] ?? '');
$country = trim($_POST['country'] ?? '');
$currency = trim($_POST['currency'] ?? 'USD');
$timezone = trim($_POST['timezone'] ?? 'UTC');
$description = trim($_POST['description'] ?? '');
$domain = trim($_POST['domain'] ?? '');
$planId = !empty($_POST['plan_id']) ? (int) $_POST['plan_id'] : null;
$status = trim($_POST['status'] ?? 'trial');
$operatingMode = (int) ($_POST['operating_mode'] ?? 1);
$maxMenuItems = (int) ($_POST['max_menu_items'] ?? 50);
$maxStaff = (int) ($_POST['max_staff'] ?? 3);
$maxTables = (int) ($_POST['max_tables'] ?? 10);
$trialStart = !empty($_POST['trial_start']) ? $_POST['trial_start'] : null;
$trialEnd = !empty($_POST['trial_end']) ? $_POST['trial_end'] : null;
$subStart = !empty($_POST['subscription_start']) ? $_POST['subscription_start'] : null;
$subEnd = !empty($_POST['subscription_end']) ? $_POST['subscription_end'] : null;

$adminName = trim($_POST['admin_name'] ?? '');
$adminEmail = trim($_POST['admin_email'] ?? '');
$adminPassword = $_POST['admin_password'] ?? '';

if (empty($name)) {
    redirect('/admin/restaurant_' . $action . '.php');
}

$upload = new Upload();
$logoPath = null;
$coverPath = null;

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

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

try {
    $db->beginTransaction();

    if ($action === 'edit' && $id > 0) {
        $updateData = [
            'name' => $name,
            'slug' => $slug,
            'owner_name' => $ownerName,
            'email' => $email,
            'phone' => $phone,
            'whatsapp' => $whatsapp,
            'address' => $address,
            'city' => $city,
            'country' => $country,
            'currency' => $currency,
            'timezone' => $timezone,
            'description' => $description,
            'domain' => $domain,
            'plan_id' => $planId,
            'status' => $status,
            'operating_mode' => $operatingMode,
            'max_menu_items' => $maxMenuItems,
            'max_staff' => $maxStaff,
            'max_tables' => $maxTables,
            'trial_start' => $trialStart,
            'trial_end' => $trialEnd,
            'subscription_start' => $subStart,
            'subscription_end' => $subEnd,
        ];

        if ($logoPath !== null) {
            $updateData['logo'] = $logoPath;
        }
        if ($coverPath !== null) {
            $updateData['cover_image'] = $coverPath;
        }

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

        $existingAdmin = $db->query("SELECT id FROM users WHERE restaurant_id = ? AND role_id = 2 LIMIT 1", [$id])->fetch();
        if ($existingAdmin) {
            $adminUpdate = ['name' => $adminName, 'email' => $adminEmail];
            if (!empty($adminPassword)) {
                $adminUpdate['password'] = password_hash($adminPassword, PASSWORD_DEFAULT);
            }
            $db->update('users', $adminUpdate, 'id = ?', [$existingAdmin['id']]);
        } else {
            if (!empty($adminPassword)) {
                $adminRoleId = $db->query("SELECT id FROM roles WHERE name = 'restaurant_admin' LIMIT 1")->fetch()['id'];
                $db->insert('users', [
                    'role_id' => $adminRoleId,
                    'restaurant_id' => $id,
                    'name' => $adminName,
                    'email' => $adminEmail,
                    'password' => password_hash($adminPassword, PASSWORD_DEFAULT),
                    'status' => 'active',
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ]);
            }
        }

        $logMessage = 'Updated restaurant: ' . $name;
    } else {
        $existingSlug = $db->query("SELECT id FROM restaurants WHERE slug = ?", [$slug])->fetch();
        if ($existingSlug) {
            $slug = $slug . '-' . strtolower(generateCode(4));
        }

        $existingCode = $db->query("SELECT id FROM restaurants WHERE code = ?", [$code])->fetch();
        if ($existingCode) {
            $code = generateCode(6);
        }

        $restaurantId = $db->insert('restaurants', [
            'name' => $name,
            'slug' => $slug,
            'code' => $code,
            'owner_name' => $ownerName,
            'email' => $email,
            'phone' => $phone,
            'whatsapp' => $whatsapp,
            'address' => $address,
            'city' => $city,
            'country' => $country,
            'currency' => $currency,
            'timezone' => $timezone,
            'logo' => $logoPath,
            'cover_image' => $coverPath,
            'description' => $description,
            'plan_id' => $planId,
            'trial_start' => $trialStart,
            'trial_end' => $trialEnd,
            'subscription_start' => $subStart,
            'subscription_end' => $subEnd,
            'status' => $status,
            'operating_mode' => $operatingMode,
            'max_menu_items' => $maxMenuItems,
            'max_staff' => $maxStaff,
            'max_tables' => $maxTables,
            'domain' => $domain,
            'is_active' => 1,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);

        $db->insert('restaurant_settings', [
            'restaurant_id' => $restaurantId,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);

        if (!empty($adminPassword)) {
            $adminRoleId = $db->query("SELECT id FROM roles WHERE name = 'restaurant_admin' LIMIT 1")->fetch()['id'];
            $db->insert('users', [
                'role_id' => $adminRoleId,
                'restaurant_id' => $restaurantId,
                'name' => $adminName,
                'email' => $adminEmail,
                'password' => password_hash($adminPassword, PASSWORD_DEFAULT),
                'status' => 'active',
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);
        }

        $id = $restaurantId;
        $logMessage = 'Created restaurant: ' . $name;
    }

    $activityLog = new ActivityLog();
    $activityLog->log(
        $_SESSION['user_id'],
        $id,
        'restaurant',
        $action,
        $logMessage,
        $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1'
    );

    $db->commit();
    redirect('/admin/restaurants.php');

} catch (Exception $e) {
    $db->rollback();
    error_log('Restaurant save error: ' . $e->getMessage());
    redirect('/admin/restaurant_' . $action . '.php');
}
