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

$db = Database::getInstance();

try {
    $db->beginTransaction();

    $adminRoleId = $db->query("SELECT id FROM roles WHERE name = 'restaurant_admin' LIMIT 1")->fetch()['id'];

    $plan = $db->query("SELECT id FROM subscription_plans WHERE slug = 'professional' LIMIT 1")->fetch();
    $planId = $plan ? $plan['id'] : null;

    $restaurants = [
        [
            'name' => 'Ocean Spice',
            'slug' => 'ocean-spice-demo',
            'code' => generateCode(6),
            'owner_name' => 'Rajesh Kumar',
            'email' => 'rajesh@oceanspice.demo',
            'phone' => '+94771234567',
            'city' => 'Colombo',
            'country' => 'Sri Lanka',
            'currency' => 'LKR',
            'operating_mode' => 1,
            'status' => 'active',
            'categories' => [
                ['name' => 'Seafood Specials', 'items' => [
                    ['name' => 'Garlic Butter Prawns', 'price' => 2200, 'desc' => 'Fresh tiger prawns sauteed in garlic butter'],
                    ['name' => 'Grilled Salmon Fillet', 'price' => 3500, 'desc' => 'Norwegian salmon grilled to perfection'],
                    ['name' => 'Fish & Chips', 'price' => 1800, 'desc' => 'Classic battered fish with crispy fries'],
                    ['name' => 'Crab Curry', 'price' => 2800, 'desc' => 'Sri Lankan style crab curry with spices'],
                ]],
                ['name' => 'Starters', 'items' => [
                    ['name' => 'Spring Rolls', 'price' => 600, 'desc' => 'Crispy vegetable spring rolls'],
                    ['name' => 'Soup of the Day', 'price' => 500, 'desc' => 'Freshly made soup'],
                    ['name' => 'Calamari Rings', 'price' => 1200, 'desc' => 'Lightly fried squid rings'],
                ]],
                ['name' => 'Beverages', 'items' => [
                    ['name' => 'Fresh Lime Soda', 'price' => 300, 'desc' => 'Refreshing lime soda'],
                    ['name' => 'Mango Lassi', 'price' => 450, 'desc' => 'Creamy mango yogurt drink'],
                    ['name' => 'Ceylon Tea', 'price' => 200, 'desc' => 'Premium Ceylon tea'],
                ]],
            ],
        ],
        [
            'name' => 'Urban Taste',
            'slug' => 'urban-taste-demo',
            'code' => generateCode(6),
            'owner_name' => 'Sarah Fernando',
            'email' => 'sarah@urbantaste.demo',
            'phone' => '+94779876543',
            'city' => 'Kandy',
            'country' => 'Sri Lanka',
            'currency' => 'LKR',
            'operating_mode' => 2,
            'status' => 'active',
            'categories' => [
                ['name' => 'Burgers', 'items' => [
                    ['name' => 'Classic Cheeseburger', 'price' => 1500, 'desc' => 'Beef patty with cheese, lettuce, tomato'],
                    ['name' => 'BBQ Bacon Burger', 'price' => 1800, 'desc' => 'Smoky BBQ sauce with crispy bacon'],
                    ['name' => 'Veggie Burger', 'price' => 1200, 'desc' => 'Plant-based patty with fresh toppings'],
                ]],
                ['name' => 'Pizza', 'items' => [
                    ['name' => 'Margherita', 'price' => 1600, 'desc' => 'Classic tomato, mozzarella, basil'],
                    ['name' => 'Pepperoni', 'price' => 1900, 'desc' => 'Loaded with pepperoni and cheese'],
                    ['name' => 'BBQ Chicken', 'price' => 2000, 'desc' => 'BBQ chicken with onions and peppers'],
                ]],
                ['name' => 'Pasta', 'items' => [
                    ['name' => 'Spaghetti Carbonara', 'price' => 1400, 'desc' => 'Creamy pasta with bacon and parmesan'],
                    ['name' => 'Penne Arrabbiata', 'price' => 1200, 'desc' => 'Spicy tomato sauce with penne'],
                ]],
                ['name' => 'Desserts', 'items' => [
                    ['name' => 'Chocolate Brownie', 'price' => 800, 'desc' => 'Warm brownie with ice cream'],
                    ['name' => 'Cheesecake', 'price' => 900, 'desc' => 'New York style cheesecake'],
                ]],
            ],
        ],
    ];

    $adminEmails = [];

    foreach ($restaurants as $restData) {
        $categories = $restData['categories'];
        unset($restData['categories']);

        $restData['plan_id'] = $planId;
        $restData['trial_start'] = date('Y-m-d');
        $restData['trial_end'] = date('Y-m-d', strtotime('+30 days'));
        $restData['is_demo'] = 1;
        $restData['is_active'] = 1;
        $restData['max_menu_items'] = 200;
        $restData['max_staff'] = 10;
        $restData['max_tables'] = 20;
        $restData['created_at'] = date('Y-m-d H:i:s');
        $restData['updated_at'] = date('Y-m-d H:i:s');

        $restId = $db->insert('restaurants', $restData);

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

        $adminEmail = 'admin_' . strtolower($restData['slug']) . '@demo.local';
        $db->insert('users', [
            'role_id' => $adminRoleId,
            'restaurant_id' => $restId,
            'name' => 'Admin ' . $restData['name'],
            'email' => $adminEmail,
            'password' => password_hash('password', PASSWORD_DEFAULT),
            'status' => 'active',
            'is_demo' => 1,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);

        $tablePrefix = ['A','B','C','D'];
        for ($t = 1; $t <= 8; $t++) {
            $area = $t <= 4 ? 'Indoor' : 'Outdoor';
            $db->insert('tables', [
                'restaurant_id' => $restId,
                'table_number' => $tablePrefix[($t - 1) % 4] . $t,
                'table_name' => 'Table ' . $t,
                'capacity' => ($t <= 4) ? 4 : 6,
                'area' => $area,
                'status' => 'available',
                'is_active' => 1,
                'is_demo' => 1,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);
        }

        $sortOrder = 0;
        foreach ($categories as $catData) {
            $items = $catData['items'];
            unset($catData['items']);

            $catId = $db->insert('categories', [
                'restaurant_id' => $restId,
                'name' => $catData['name'],
                'slug' => slugify($catData['name']),
                'status' => 1,
                'sort_order' => $sortOrder++,
                'is_demo' => 1,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);

            $itemSort = 0;
            foreach ($items as $itemData) {
                $db->insert('menu_items', [
                    'restaurant_id' => $restId,
                    'category_id' => $catId,
                    'name' => $itemData['name'],
                    'slug' => slugify($itemData['name']),
                    'short_description' => $itemData['desc'],
                    'regular_price' => $itemData['price'],
                    'is_available' => 1,
                    'is_featured' => ($itemSort === 0) ? 1 : 0,
                    'sort_order' => $itemSort++,
                    'is_demo' => 1,
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ]);
            }
        }

        if ($restData['operating_mode'] == 2) {
            for ($o = 0; $o < 5; $o++) {
                $orderDate = date('Y-m-d H:i:s', strtotime("-{$o} days"));
                $orderNum = 'ORD' . date('ymd', strtotime($orderDate)) . str_pad($o + 1, 4, '0', STR_PAD_LEFT);
                $subtotal = rand(1500, 5000) / 100;
                $subtotal = round($subtotal, 2);
                $tax = round($subtotal * 0.05, 2);
                $total = round($subtotal + $tax, 2);

                $orderId = $db->insert('orders', [
                    'restaurant_id' => $restId,
                    'order_number' => $orderNum,
                    'order_type' => ($o % 2 == 0) ? 'dine_in' : 'takeaway',
                    'customer_name' => 'Customer ' . ($o + 1),
                    'customer_phone' => '+94771000' . str_pad($o, 3, '0', STR_PAD_LEFT),
                    'subtotal' => $subtotal,
                    'tax' => $tax,
                    'grand_total' => $total,
                    'payment_status' => 'paid',
                    'order_status' => 'completed',
                    'is_demo' => 1,
                    'created_at' => $orderDate,
                    'updated_at' => $orderDate,
                ]);
            }
        }
    }

    $activityLog = new ActivityLog();
    $activityLog->log($_SESSION['user_id'], null, 'demo', 'install', 'Installed demo data: 2 restaurants with categories, items, tables, and orders');

    $db->commit();
    jsonResponse(true, 'Demo data installed successfully! 2 restaurants with all data created.');

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