<?php
$pageTitle = 'View Restaurant';
require_once __DIR__ . '/includes/header.php';

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

if ($id <= 0) {
    redirect($baseUrl . '/admin/restaurants.php');
}

$restaurant = $db->query("SELECT r.*, sp.name as plan_name FROM restaurants r LEFT JOIN subscription_plans sp ON r.plan_id = sp.id WHERE r.id = ?", [$id])->fetch();
if (!$restaurant) {
    redirect($baseUrl . '/admin/restaurants.php');
}

$totalOrders = $db->count('orders', 'restaurant_id = ?', [$id]);
$ordersToday = $db->count('orders', 'restaurant_id = ? AND DATE(created_at) = CURDATE()', [$id]);
$totalMenuItems = $db->count('menu_items', 'restaurant_id = ?', [$id]);
$totalCategories = $db->count('categories', 'restaurant_id = ?', [$id]);
$totalTables = $db->count('tables', 'restaurant_id = ?', [$id]);
$totalCustomers = $db->count('customers', 'restaurant_id = ?', [$id]);
$totalStaff = $db->count('users', 'restaurant_id = ?', [$id]);

$stmtRevenue = $db->query("SELECT COALESCE(SUM(grand_total), 0) as total FROM orders WHERE restaurant_id = ? AND payment_status = 'paid'", [$id]);
$revenue = $stmtRevenue->fetch()['total'];

$adminUser = $db->query("SELECT * FROM users WHERE restaurant_id = ? AND role_id = 2 LIMIT 1", [$id])->fetch();

$recentOrders = $db->query("SELECT * FROM orders WHERE restaurant_id = ? ORDER BY created_at DESC LIMIT 5", [$id])->fetchAll();

$activityLogs = $db->query("
    SELECT al.*, u.name as user_name
    FROM activity_logs al
    LEFT JOIN users u ON al.user_id = u.id
    WHERE al.restaurant_id = ?
    ORDER BY al.created_at DESC
    LIMIT 10
", [$id])->fetchAll();
?>

<div class="row mb-4">
    <div class="col-md-8">
        <div class="form-card">
            <div class="d-flex justify-content-between align-items-start mb-3">
                <div>
                    <h4 class="mb-1"><?php echo sanitize($restaurant['name']); ?></h4>
                    <span class="text-muted">Code: <?php echo sanitize($restaurant['code']); ?> | Slug: <?php echo sanitize($restaurant['slug']); ?></span>
                </div>
                <div>
                    <?php
                    $statusClass = ['active'=>'success','trial'=>'warning','suspended'=>'danger','expired'=>'secondary','cancelled'=>'dark'];
                    $cls = $statusClass[$restaurant['status']] ?? 'secondary';
                    ?>
                    <span class="badge bg-<?php echo $cls; ?> fs-6"><?php echo ucfirst(sanitize($restaurant['status'])); ?></span>
                </div>
            </div>

            <div class="row g-3">
                <div class="col-md-6">
                    <strong>Owner:</strong> <?php echo sanitize($restaurant['owner_name'] ?? 'N/A'); ?>
                </div>
                <div class="col-md-6">
                    <strong>Email:</strong> <?php echo sanitize($restaurant['email'] ?? 'N/A'); ?>
                </div>
                <div class="col-md-6">
                    <strong>Phone:</strong> <?php echo sanitize($restaurant['phone'] ?? 'N/A'); ?>
                </div>
                <div class="col-md-6">
                    <strong>WhatsApp:</strong> <?php echo sanitize($restaurant['whatsapp'] ?? 'N/A'); ?>
                </div>
                <div class="col-md-6">
                    <strong>City:</strong> <?php echo sanitize($restaurant['city'] ?? 'N/A'); ?>
                </div>
                <div class="col-md-6">
                    <strong>Country:</strong> <?php echo sanitize($restaurant['country'] ?? 'N/A'); ?>
                </div>
                <div class="col-md-6">
                    <strong>Currency:</strong> <?php echo sanitize($restaurant['currency']); ?>
                </div>
                <div class="col-md-6">
                    <strong>Mode:</strong> <?php echo $restaurant['operating_mode'] == 1 ? 'View Only' : 'Ordering'; ?>
                </div>
                <div class="col-md-12">
                    <strong>Address:</strong> <?php echo sanitize($restaurant['address'] ?? 'N/A'); ?>
                </div>
                <?php if (!empty($restaurant['description'])): ?>
                <div class="col-md-12">
                    <strong>Description:</strong> <?php echo sanitize($restaurant['description']); ?>
                </div>
                <?php endif; ?>
                <?php if (!empty($restaurant['domain'])): ?>
                <div class="col-md-6">
                    <strong>Domain:</strong> <?php echo sanitize($restaurant['domain']); ?>
                </div>
                <?php endif; ?>
                <div class="col-md-6">
                    <strong>Created:</strong> <?php echo formatDateTime($restaurant['created_at']); ?>
                </div>
            </div>
        </div>
    </div>

    <div class="col-md-4">
        <div class="form-card">
            <h6 class="text-primary mb-3">Subscription Details</h6>
            <div class="mb-2"><strong>Plan:</strong> <span class="badge bg-info"><?php echo sanitize($restaurant['plan_name'] ?? 'None'); ?></span></div>
            <div class="mb-2"><strong>Trial:</strong> <?php echo $restaurant['trial_start'] ? formatDate($restaurant['trial_start']) . ' to ' . formatDate($restaurant['trial_end']) : 'N/A'; ?></div>
            <div class="mb-2"><strong>Subscription:</strong> <?php echo $restaurant['subscription_start'] ? formatDate($restaurant['subscription_start']) . ' to ' . formatDate($restaurant['subscription_end']) : 'N/A'; ?></div>
            <div class="mb-2"><strong>Max Menu Items:</strong> <?php echo $restaurant['max_menu_items']; ?></div>
            <div class="mb-2"><strong>Max Staff:</strong> <?php echo $restaurant['max_staff']; ?></div>
            <div class="mb-2"><strong>Max Tables:</strong> <?php echo $restaurant['max_tables']; ?></div>
            <hr>
            <div class="d-flex gap-2">
                <a href="restaurant_edit.php?id=<?php echo $id; ?>" class="btn btn-sm btn-primary"><i class="fas fa-edit me-1"></i>Edit</a>
                <a href="<?php echo $baseUrl; ?>/restaurant-admin/?rid=<?php echo $restaurant['code']; ?>" class="btn btn-sm btn-outline-secondary" target="_blank"><i class="fas fa-external-link-alt me-1"></i>View Panel</a>
            </div>
        </div>

        <?php if ($adminUser): ?>
        <div class="form-card">
            <h6 class="text-primary mb-3">Admin Account</h6>
            <div class="mb-1"><strong>Name:</strong> <?php echo sanitize($adminUser['name']); ?></div>
            <div class="mb-1"><strong>Email:</strong> <?php echo sanitize($adminUser['email']); ?></div>
            <div class="mb-1"><strong>Status:</strong> <span class="badge bg-<?php echo $adminUser['status'] === 'active' ? 'success' : 'secondary'; ?>"><?php echo ucfirst($adminUser['status']); ?></span></div>
            <div class="mb-1"><strong>Last Login:</strong> <?php echo $adminUser['last_login'] ? timeAgo($adminUser['last_login']) : 'Never'; ?></div>
        </div>
        <?php endif; ?>
    </div>
</div>

<div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="stat-card" style="border-left-color:#4f46e5;">
            <div class="stat-value"><?php echo number_format($totalOrders); ?></div>
            <div class="stat-label">Total Orders</div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="stat-card" style="border-left-color:#10b981;">
            <div class="stat-value"><?php echo number_format($ordersToday); ?></div>
            <div class="stat-label">Orders Today</div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="stat-card" style="border-left-color:#6366f1;">
            <div class="stat-value"><?php echo number_format($totalMenuItems); ?></div>
            <div class="stat-label">Menu Items</div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="stat-card" style="border-left-color:#14b8a6;">
            <div class="stat-value"><?php echo formatCurrency($revenue); ?></div>
            <div class="stat-label">Revenue</div>
        </div>
    </div>
</div>

<div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="stat-card" style="border-left-color:#f59e0b;">
            <div class="stat-value"><?php echo number_format($totalCategories); ?></div>
            <div class="stat-label">Categories</div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="stat-card" style="border-left-color:#ec4899;">
            <div class="stat-value"><?php echo number_format($totalTables); ?></div>
            <div class="stat-label">Tables</div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="stat-card" style="border-left-color:#8b5cf6;">
            <div class="stat-value"><?php echo number_format($totalCustomers); ?></div>
            <div class="stat-label">Customers</div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="stat-card" style="border-left-color:#ef4444;">
            <div class="stat-value"><?php echo number_format($totalStaff); ?></div>
            <div class="stat-label">Staff Members</div>
        </div>
    </div>
</div>

<div class="row mb-4">
    <div class="col-xl-8 mb-3">
        <div class="table-card">
            <div class="card-header"><i class="fas fa-receipt me-2"></i>Recent Orders</div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr><th>Order #</th><th>Type</th><th>Total</th><th>Status</th><th>Date</th></tr>
                        </thead>
                        <tbody>
                            <?php if (empty($recentOrders)): ?>
                                <tr><td colspan="5" class="text-center text-muted py-3">No orders yet</td></tr>
                            <?php else: ?>
                                <?php foreach ($recentOrders as $order): ?>
                                <tr>
                                    <td><strong><?php echo sanitize($order['order_number']); ?></strong></td>
                                    <td><?php echo ucfirst(str_replace('_', ' ', $order['order_type'])); ?></td>
                                    <td><?php echo formatCurrency($order['grand_total']); ?></td>
                                    <td><span class="badge bg-<?php echo $order['order_status'] === 'completed' ? 'success' : ($order['order_status'] === 'cancelled' ? 'danger' : 'warning'); ?>"><?php echo ucfirst($order['order_status']); ?></span></td>
                                    <td><?php echo timeAgo($order['created_at']); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-4 mb-3">
        <div class="table-card">
            <div class="card-header"><i class="fas fa-history me-2"></i>Activity Log</div>
            <div class="card-body">
                <?php if (empty($activityLogs)): ?>
                    <div class="text-center text-muted py-3">No activity logged</div>
                <?php else: ?>
                    <?php foreach ($activityLogs as $log): ?>
                    <div class="border-bottom py-2">
                        <div class="small"><strong><?php echo sanitize($log['user_name'] ?? 'System'); ?></strong> - <?php echo sanitize($log['action']); ?></div>
                        <div class="text-muted" style="font-size:11px;"><?php echo sanitize($log['details']); ?></div>
                        <div class="text-muted" style="font-size:10px;"><?php echo timeAgo($log['created_at']); ?></div>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
