<?php
// shop_details.php
declare(strict_types=1);
session_start();

require_once '../config/db_connect.php';

// Start output buffering
ob_start();

require_once '../includes/header.php';
require_once '../includes/sidebar.php';

if (!isset($_SESSION['user'])) { 
    header('Location: login.php');
    exit; 
}

$shop_id = (int)($_GET['id'] ?? 0);
if (!$shop_id) {
    header('Location: shops.php');
    exit;
}

// Get shop details
$stmt = $pdo->prepare("
    SELECT s.*, 
           creator.fullname as created_by_name,
           updater.fullname as updated_by_name
    FROM shops s
    LEFT JOIN users creator ON s.created_by = creator.id
    LEFT JOIN users updater ON s.updated_by = updater.id
    WHERE s.id = ?
");
$stmt->execute([$shop_id]);
$shop = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$shop) {
    echo "<div class='col-md-10 ml-sm-auto px-4 py-4'><div class='alert alert-danger'>Shop not found.</div></div>";
    require_once '../includes/footer.php';
    exit;
}

// Get shop statistics
$stats_sql = "
    SELECT 
        (SELECT COUNT(*) FROM users WHERE shop_id = ?) as user_count,
        (SELECT COUNT(*) FROM products WHERE shop_id = ?) as product_count,
        (SELECT COUNT(*) FROM sales WHERE shop_id = ?) as sale_count,
        (SELECT SUM(total) FROM sales WHERE shop_id = ?) as total_revenue,
        (SELECT COUNT(*) FROM customers WHERE shop_id = ?) as customer_count,
        (SELECT COUNT(*) FROM product_batches WHERE shop_id = ?) as batch_count
";

$stats_stmt = $pdo->prepare($stats_sql);
$stats_stmt->execute([$shop_id, $shop_id, $shop_id, $shop_id, $shop_id, $shop_id]);
$stats = $stats_stmt->fetch(PDO::FETCH_ASSOC);

// Get recent sales
$sales_sql = "
    SELECT s.*, c.name as customer_name, u.fullname as cashier
    FROM sales s
    LEFT JOIN customers c ON s.customer_id = c.id
    LEFT JOIN users u ON s.created_by = u.id
    WHERE s.shop_id = ?
    ORDER BY s.sale_date DESC
    LIMIT 10
";
$sales_stmt = $pdo->prepare($sales_sql);
$sales_stmt->execute([$shop_id]);
$recent_sales = $sales_stmt->fetchAll(PDO::FETCH_ASSOC);

// Get shop users
$users_sql = "
    SELECT u.*, COUNT(s.id) as sale_count
    FROM users u
    LEFT JOIN sales s ON u.id = s.created_by AND s.shop_id = ?
    WHERE u.shop_id = ?
    GROUP BY u.id
    ORDER BY u.role, u.fullname
";
$users_stmt = $pdo->prepare($users_sql);
$users_stmt->execute([$shop_id, $shop_id]);
$shop_users = $users_stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!-- Add similar stunning CSS as shops.php -->
<!-- Create a beautiful shop dashboard with tabs for:
     1. Overview (stats)
     2. Users
     3. Recent Sales
     4. Products
     5. Settings
-->
<?php 
require_once '../includes/footer.php'; 
ob_end_flush();
?>