<?php
// app/Controllers/RestaurantController.php

class RestaurantController {
    private function requireSuperAdmin() {
        if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'superadmin') {
            header('Location: /restpo/login'); exit;
        }
    }

    public function index() {
        $this->requireSuperAdmin();
        $db = getDB();
        $pageTitle = 'Manage Restaurants';

        $stmt = $db->query('
            SELECT r.*, p.name as package_name
            FROM restaurants r
            LEFT JOIN subscriptions s ON s.restaurant_id = r.id AND s.status="active"
            LEFT JOIN packages p ON p.id = s.package_id
            ORDER BY r.created_at DESC
        ');
        $restaurants = $stmt->fetchAll();

        ob_start();
        require 'app/Views/superadmin/restaurants/list.php';
        $content = ob_get_clean();
        require 'app/Views/layouts/superadmin.php';
    }

    public function create() {
        $this->requireSuperAdmin();
        $db = getDB();
        $pageTitle = 'Add Restaurant';
        $packages = $db->query('SELECT * FROM packages WHERE status="active"')->fetchAll();

        ob_start();
        require 'app/Views/superadmin/restaurants/form.php';
        $content = ob_get_clean();
        require 'app/Views/layouts/superadmin.php';
    }

    public function store() {
        $this->requireSuperAdmin();

        $db = getDB();
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $adminEmail = trim($_POST['admin_email'] ?? '');
        $adminName = trim($_POST['admin_name'] ?? '');
        $adminPassword = $_POST['admin_password'] ?? '';

        if (!$name || !$adminEmail || !$adminName || !$adminPassword) {
            header('Location: /restpo/superadmin/restaurants/create?error=' . urlencode('Name, Admin Name, Admin Email, and Password are required.')); exit;
        }

        // Check duplicate email in restaurants
        if ($email !== '') {
            $stmt = $db->prepare('SELECT COUNT(*) FROM restaurants WHERE email = ?');
            $stmt->execute([$email]);
            if ($stmt->fetchColumn() > 0) {
                header('Location: /restpo/superadmin/restaurants/create?error=' . urlencode('Restaurant email address is already in use.')); exit;
            }
        }

        // Check duplicate phone in restaurants
        if ($phone !== '') {
            $stmt = $db->prepare('SELECT COUNT(*) FROM restaurants WHERE phone = ?');
            $stmt->execute([$phone]);
            if ($stmt->fetchColumn() > 0) {
                header('Location: /restpo/superadmin/restaurants/create?error=' . urlencode('Restaurant phone number is already in use.')); exit;
            }
        }

        // Check duplicate admin email in users
        $stmt = $db->prepare('SELECT COUNT(*) FROM users WHERE email = ?');
        $stmt->execute([$adminEmail]);
        if ($stmt->fetchColumn() > 0) {
            header('Location: /restpo/superadmin/restaurants/create?error=' . urlencode('Admin email address is already in use by a user.')); exit;
        }

        $currency = trim($_POST['currency'] ?? '$');
        $db->beginTransaction();
        try {
            $extra_features = array_filter([
                'max_floors' => $_POST['override_max_floors'] !== '' ? (int)$_POST['override_max_floors'] : null,
                'max_tables' => $_POST['override_max_tables'] !== '' ? (int)$_POST['override_max_tables'] : null,
                'max_cashiers' => $_POST['override_max_cashiers'] !== '' ? (int)$_POST['override_max_cashiers'] : null,
                'max_waiters' => $_POST['override_max_waiters'] !== '' ? (int)$_POST['override_max_waiters'] : null,
                'qr_ordering' => isset($_POST['override_qr_ordering']) ? true : null,
                'kitchen_display' => isset($_POST['override_kitchen_display']) ? true : null,
                'is_lifetime' => isset($_POST['override_is_lifetime']) ? true : null,
            ], function($v) { return $v !== null; });
            $extra_features_json = json_encode($extra_features);

            $stmt = $db->prepare('INSERT INTO restaurants (name, email, phone, currency, status, extra_features) VALUES (?, ?, ?, ?, "active", ?)');
            $stmt->execute([$_POST['name'], $_POST['email'], $_POST['phone'], $currency, $extra_features_json]);
            $restaurant_id = $db->lastInsertId();

            $hashed = password_hash($_POST['admin_password'], PASSWORD_BCRYPT);
            $db->prepare('INSERT INTO users (restaurant_id, name, email, password, role) VALUES (?, ?, ?, ?, "admin")')
               ->execute([$restaurant_id, $_POST['admin_name'], $_POST['admin_email'], $hashed]);

            if (!empty($_POST['package_id'])) {
                $pkg = $db->prepare('SELECT * FROM packages WHERE id = ?');
                $pkg->execute([$_POST['package_id']]);
                $pkg = $pkg->fetch();
                if ($pkg) {
                    $pkgFeatures = json_decode($pkg['features'] ?? '{}', true) ?: [];
                    $isLifetime = !empty($pkgFeatures['is_lifetime']) || isset($_POST['override_is_lifetime']);
                    $end = $isLifetime ? '2099-12-31' : date('Y-m-d', strtotime('+' . $pkg['duration_days'] . ' days'));
                    
                    $db->prepare('INSERT INTO subscriptions (restaurant_id, package_id, start_date, end_date, amount, payment_status, status) VALUES (?, ?, CURDATE(), ?, ?, "paid", "active")')
                       ->execute([$restaurant_id, $pkg['id'], $end, $pkg['price']]);
                    $db->prepare('UPDATE restaurants SET subscription_ends_at=? WHERE id=?')
                       ->execute([$end . ' 23:59:59', $restaurant_id]);
                }
            }

            // Send confirmation email if checkbox was selected
            if (isset($_POST['send_welcome_email'])) {
                try {
                    // Send to admin email
                    MailHelper::sendWelcomeEmail($_POST['admin_email'], $_POST['admin_name'], $_POST['name']);
                    
                    // Send to restaurant email if different and not empty
                    $restaurantEmail = trim($_POST['email'] ?? '');
                    if ($restaurantEmail !== '' && $restaurantEmail !== $_POST['admin_email']) {
                        MailHelper::sendWelcomeEmail($restaurantEmail, $_POST['admin_name'], $_POST['name']);
                    }
                } catch (\Exception $mailEx) {
                    // Do not block transaction
                }
            }

            $db->commit();
            header('Location: /restpo/superadmin/restaurants?success=1'); exit;
        } catch (\Exception $e) {
            $db->rollBack();
            header('Location: /restpo/superadmin/restaurants/create?error=' . urlencode($e->getMessage())); exit;
        }
    }

    public function edit() {
        $this->requireSuperAdmin();
        $db = getDB();
        $id = $_GET['id'] ?? null;
        if (!$id) { header('Location: /restpo/superadmin/restaurants'); exit; }

        $restaurant = $db->prepare('SELECT * FROM restaurants WHERE id = ?');
        $restaurant->execute([$id]);
        $restaurant = $restaurant->fetch();
        if (!$restaurant) { header('Location: /restpo/superadmin/restaurants?error=Restaurant+not+found'); exit; }

        $packages = $db->query('SELECT * FROM packages WHERE status="active"')->fetchAll();

        // Get current active subscription
        $sub = $db->prepare('SELECT * FROM subscriptions WHERE restaurant_id = ? AND status = "active" LIMIT 1');
        $sub->execute([$id]);
        $activeSub = $sub->fetch();

        // Get admin user details
        $adminStmt = $db->prepare('SELECT * FROM users WHERE restaurant_id = ? AND role = "admin" LIMIT 1');
        $adminStmt->execute([$id]);
        $adminUser = $adminStmt->fetch();

        $pageTitle = 'Edit Restaurant';

        ob_start();
        require 'app/Views/superadmin/restaurants/edit.php';
        $content = ob_get_clean();
        require 'app/Views/layouts/superadmin.php';
    }

    public function update() {
        $this->requireSuperAdmin();
        $db = getDB();
        $id = $_POST['id'] ?? null;
        if (!$id) { header('Location: /restpo/superadmin/restaurants'); exit; }

        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $currency = trim($_POST['currency'] ?? '$');
        $status = trim($_POST['status'] ?? 'active');
        $packageId = $_POST['package_id'] ?? '';

        if (!$name) {
            header('Location: /restpo/superadmin/restaurants/edit?id=' . $id . '&error=' . urlencode('Restaurant name is required.')); exit;
        }

        // Check duplicate email in restaurants
        if ($email !== '') {
            $stmt = $db->prepare('SELECT COUNT(*) FROM restaurants WHERE email = ? AND id != ?');
            $stmt->execute([$email, $id]);
            if ($stmt->fetchColumn() > 0) {
                header('Location: /restpo/superadmin/restaurants/edit?id=' . $id . '&error=' . urlencode('Restaurant email address is already in use.')); exit;
            }
        }

        // Check duplicate phone in restaurants
        if ($phone !== '') {
            $stmt = $db->prepare('SELECT COUNT(*) FROM restaurants WHERE phone = ? AND id != ?');
            $stmt->execute([$phone, $id]);
            if ($stmt->fetchColumn() > 0) {
                header('Location: /restpo/superadmin/restaurants/edit?id=' . $id . '&error=' . urlencode('Restaurant phone number is already in use.')); exit;
            }
        }

        $db->beginTransaction();
        try {
            $extra_features = array_filter([
                'max_floors' => $_POST['override_max_floors'] !== '' ? (int)$_POST['override_max_floors'] : null,
                'max_tables' => $_POST['override_max_tables'] !== '' ? (int)$_POST['override_max_tables'] : null,
                'max_cashiers' => $_POST['override_max_cashiers'] !== '' ? (int)$_POST['override_max_cashiers'] : null,
                'max_waiters' => $_POST['override_max_waiters'] !== '' ? (int)$_POST['override_max_waiters'] : null,
                'qr_ordering' => isset($_POST['override_qr_ordering']) ? true : null,
                'kitchen_display' => isset($_POST['override_kitchen_display']) ? true : null,
                'is_lifetime' => isset($_POST['override_is_lifetime']) ? true : null,
            ], function($v) { return $v !== null; });
            $extra_features_json = json_encode($extra_features);

            // Update restaurants table
            $db->prepare('UPDATE restaurants SET name = ?, email = ?, phone = ?, currency = ?, status = ?, extra_features = ? WHERE id = ?')
               ->execute([$name, $email, $phone, $currency, $status, $extra_features_json, $id]);

            // Update admin user credentials if provided
            $adminName = trim($_POST['admin_name'] ?? '');
            $adminEmail = trim($_POST['admin_email'] ?? '');
            $adminPassword = $_POST['admin_password'] ?? '';

            if ($adminName && $adminEmail) {
                // Find admin user
                $adminStmt = $db->prepare('SELECT id FROM users WHERE restaurant_id = ? AND role = "admin" LIMIT 1');
                $adminStmt->execute([$id]);
                $adminUser = $adminStmt->fetch();

                if ($adminUser) {
                    // Check if email is taken by someone else
                    $emailCheck = $db->prepare('SELECT COUNT(*) FROM users WHERE email = ? AND id != ?');
                    $emailCheck->execute([$adminEmail, $adminUser['id']]);
                    if ($emailCheck->fetchColumn() > 0) {
                        throw new \Exception('Admin email address is already in use.');
                    }

                    if ($adminPassword !== '') {
                        $hashed = password_hash($adminPassword, PASSWORD_BCRYPT);
                        $db->prepare('UPDATE users SET name = ?, email = ?, password = ? WHERE id = ?')
                           ->execute([$adminName, $adminEmail, $hashed, $adminUser['id']]);
                    } else {
                        $db->prepare('UPDATE users SET name = ?, email = ? WHERE id = ?')
                           ->execute([$adminName, $adminEmail, $adminUser['id']]);
                    }
                } else {
                    // If no admin exists somehow, create one
                    $hashed = password_hash($adminPassword !== '' ? $adminPassword : 'admin123', PASSWORD_BCRYPT);
                    $db->prepare('INSERT INTO users (restaurant_id, name, email, password, role) VALUES (?, ?, ?, ?, "admin")')
                       ->execute([$id, $adminName, $adminEmail, $hashed]);
                }
            }

            // Get current active subscription
            $sub = $db->prepare('SELECT * FROM subscriptions WHERE restaurant_id = ? AND status = "active" LIMIT 1');
            $sub->execute([$id]);
            $currentSub = $sub->fetch();

            $currentPackageId = $currentSub ? $currentSub['package_id'] : '';

            // If package_id has changed
            if ($packageId != $currentPackageId) {
                // Deactivate current active subscriptions
                $db->prepare('UPDATE subscriptions SET status = "cancelled" WHERE restaurant_id = ? AND status = "active"')->execute([$id]);

                if (!empty($packageId)) {
                    // Fetch new package
                    $pkgStmt = $db->prepare('SELECT * FROM packages WHERE id = ?');
                    $pkgStmt->execute([$packageId]);
                    $pkg = $pkgStmt->fetch();
                    if ($pkg) {
                        $pkgFeatures = json_decode($pkg['features'] ?? '{}', true) ?: [];
                        $isLifetime = !empty($pkgFeatures['is_lifetime']) || isset($_POST['override_is_lifetime']);
                        $endDate = $isLifetime ? '2099-12-31' : date('Y-m-d', strtotime('+' . $pkg['duration_days'] . ' days'));
                        
                        $db->prepare('INSERT INTO subscriptions (restaurant_id, package_id, start_date, end_date, amount, payment_status, status) VALUES (?, ?, CURDATE(), ?, ?, "paid", "active")')
                           ->execute([$id, $pkg['id'], $endDate, $pkg['price']]);
                        
                        $db->prepare('UPDATE restaurants SET subscription_ends_at = ? WHERE id = ?')
                           ->execute([$endDate . ' 23:59:59', $id]);
                    }
                } else {
                    // No package, clear ends_at
                    $db->prepare('UPDATE restaurants SET subscription_ends_at = NULL WHERE id = ?')
                       ->execute([$id]);
                }
            } else {
                // If package didn't change but lifetime override changed, update current active subscription dates
                if (isset($_POST['override_is_lifetime'])) {
                    $db->prepare('UPDATE subscriptions SET end_date = "2099-12-31" WHERE restaurant_id = ? AND status = "active"')->execute([$id]);
                    $db->prepare('UPDATE restaurants SET subscription_ends_at = "2099-12-31 23:59:59" WHERE id = ?')->execute([$id]);
                }
            }

            $db->commit();
            header('Location: /restpo/superadmin/restaurants?success=edit'); exit;
        } catch (\Exception $e) {
            $db->rollBack();
            header('Location: /restpo/superadmin/restaurants/edit?id=' . $id . '&error=' . urlencode($e->getMessage())); exit;
        }
    }

    public function delete() {
        $this->requireSuperAdmin();
        $db = getDB();
        $id = $_POST['id'] ?? null;
        if (!$id) {
            header('Location: /restpo/superadmin/restaurants?error=Invalid+restaurant+ID'); exit;
        }

        $db->beginTransaction();
        try {
            // Delete order_items first
            $db->prepare('DELETE FROM order_items WHERE order_id IN (SELECT id FROM orders WHERE restaurant_id = ?)')
               ->execute([$id]);

            // List of tables containing restaurant_id
            $tables = [
                'attendance_logs',
                'cashier_locations',
                'categories',
                'expenses',
                'feedbacks',
                'floors',
                'inventory_categories',
                'inventory_items',
                'inventory_logs',
                'inventory_suppliers',
                'leave_balances',
                'leave_requests',
                'leave_types',
                'notifications',
                'orders',
                'payments',
                'payroll_records',
                'products',
                'restaurant_coupons',
                'restaurant_settings',
                'sessions',
                'shift_schedules',
                'staff_profiles',
                'subscriptions',
                'tables',
                'users',
                'void_logs'
            ];

            foreach ($tables as $table) {
                $db->prepare("DELETE FROM `$table` WHERE restaurant_id = ?")->execute([$id]);
            }

            // Finally delete the restaurant
            $db->prepare('DELETE FROM restaurants WHERE id = ?')->execute([$id]);

            $db->commit();
            header('Location: /restpo/superadmin/restaurants?success=delete'); exit;
        } catch (\Exception $e) {
            $db->rollBack();
            header('Location: /restpo/superadmin/restaurants?error=' . urlencode($e->getMessage())); exit;
        }
    }

    public function billing() {
        $this->requireSuperAdmin();
        $db = getDB();
        $id = $_GET['id'] ?? null;
        if (!$id) { header('Location: /restpo/superadmin/restaurants'); exit; }

        $restaurant = $db->prepare('SELECT * FROM restaurants WHERE id = ?');
        $restaurant->execute([$id]);
        $restaurant = $restaurant->fetch();
        if (!$restaurant) { header('Location: /restpo/superadmin/restaurants?error=Restaurant+not+found'); exit; }

        // Date range filters
        $startDate = !empty($_GET['start_date']) ? $_GET['start_date'] : null;
        $endDate = !empty($_GET['end_date']) ? $_GET['end_date'] : null;

        // Fetch revenue stats (Today, Week, Month, All-Time)
        $statsStmt = $db->prepare('
            SELECT 
                COALESCE(SUM(CASE WHEN payment_status = "paid" THEN amount ELSE 0 END), 0) as all_time_revenue,
                COALESCE(SUM(CASE WHEN payment_status = "paid" AND DATE(created_at) = CURDATE() THEN amount ELSE 0 END), 0) as today_revenue,
                COALESCE(SUM(CASE WHEN payment_status = "paid" AND YEARWEEK(created_at, 1) = YEARWEEK(CURDATE(), 1) THEN amount ELSE 0 END), 0) as week_revenue,
                COALESCE(SUM(CASE WHEN payment_status = "paid" AND MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN amount ELSE 0 END), 0) as month_revenue
            FROM subscriptions 
            WHERE restaurant_id = ?
        ');
        $statsStmt->execute([$id]);
        $revenueStats = $statsStmt->fetch();

        // Custom date range revenue
        $customRevenue = 0.00;
        if ($startDate && $endDate) {
            $customStmt = $db->prepare('
                SELECT COALESCE(SUM(amount), 0) as custom_revenue 
                FROM subscriptions 
                WHERE restaurant_id = ? 
                  AND payment_status = "paid" 
                  AND DATE(created_at) BETWEEN ? AND ?
            ');
            $customStmt->execute([$id, $startDate, $endDate]);
            $customRevenue = $customStmt->fetchColumn();
        }

        // Fetch subscriptions billing details (all or filtered by date range if provided)
        $subQuery = '
            SELECT s.*, p.name as package_name, p.price as package_price
            FROM subscriptions s
            JOIN packages p ON p.id = s.package_id
            WHERE s.restaurant_id = ?
        ';
        $params = [$id];

        if ($startDate && $endDate) {
            $subQuery .= " AND DATE(s.created_at) BETWEEN ? AND ?";
            $params[] = $startDate;
            $params[] = $endDate;
        }

        $subQuery .= ' ORDER BY s.id DESC';
        $historyStmt = $db->prepare($subQuery);
        $historyStmt->execute($params);
        $billingHistory = $historyStmt->fetchAll();

        // Get current active subscription
        $sub = $db->prepare('
            SELECT s.*, p.name as package_name 
            FROM subscriptions s 
            JOIN packages p ON p.id = s.package_id 
            WHERE s.restaurant_id = ? AND s.status = "active" 
            LIMIT 1
        ');
        $sub->execute([$id]);
        $activeSub = $sub->fetch();

        $pageTitle = "Billing - " . $restaurant['name'];

        ob_start();
        require 'app/Views/superadmin/restaurants/billing.php';
        $content = ob_get_clean();
        require 'app/Views/layouts/superadmin.php';
    }
}
