<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * POS Dashboard - COMPLETE FIXED VERSION
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Load the universal initializer (go up one level from /pos/ to root)
require_once dirname(__DIR__) . '/config/init.php';

// Require authentication
require_auth();

// Set page title
$page_title = 'POS Dashboard';

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;
$user_id = $current_user['user_id'] ?? 0;

if (!$user_id) {
    if (function_exists('redirect')) {
        redirect('login.php');
    } else {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

// Get date ranges
$today = date('Y-m-d');
$yesterday = date('Y-m-d', strtotime('-1 day'));

// Initialize stats array
$stats = [
    'sales_today' => 0,
    'transactions_today' => 0,
    'items_sold_today' => 0,
    'sales_yesterday' => 0,
    'active_shifts' => 0,
    'my_shift' => null,
    'cash_sales' => 0,
    'card_sales' => 0,
    'mobile_sales' => 0,
    'room_charge_sales' => 0,
    'avg_ticket' => 0
];

// Get POS statistics with error handling
try {
    // Today's sales
    $stats['sales_today'] = (float)db_fetch_value("
        SELECT COALESCE(SUM(total_amount), 0) FROM pos_sales 
        WHERE DATE(sale_time) = CURDATE()
        AND payment_status = 'completed'
    ") ?: 0;
    
    $stats['transactions_today'] = (int)db_fetch_value("
        SELECT COUNT(*) FROM pos_sales 
        WHERE DATE(sale_time) = CURDATE()
        AND payment_status = 'completed'
    ") ?: 0;
    
    $stats['items_sold_today'] = (int)db_fetch_value("
        SELECT COALESCE(SUM(quantity), 0) FROM pos_sale_items si
        JOIN pos_sales s ON si.sale_id = s.sale_id
        WHERE DATE(s.sale_time) = CURDATE()
        AND s.payment_status = 'completed'
    ") ?: 0;
    
    // Yesterday's sales
    $stats['sales_yesterday'] = (float)db_fetch_value("
        SELECT COALESCE(SUM(total_amount), 0) FROM pos_sales 
        WHERE DATE(sale_time) = ?
        AND payment_status = 'completed'
    ", [$yesterday]) ?: 0;
    
    // Current shift
    $stats['active_shifts'] = (int)db_fetch_value("
        SELECT COUNT(*) FROM pos_shifts 
        WHERE status = 'open'
    ") ?: 0;
    
    if ($user_id > 0) {
        $stats['my_shift'] = db_fetch_value("
            SELECT shift_id FROM pos_shifts 
            WHERE user_id = ? AND status = 'open'
        ", [$user_id]);
    }
    
    // Payment method breakdown
    $stats['cash_sales'] = (float)db_fetch_value("
        SELECT COALESCE(SUM(total_amount), 0) FROM pos_sales 
        WHERE DATE(sale_time) = CURDATE()
        AND payment_status = 'completed'
        AND payment_method = 'cash'
    ") ?: 0;
    
    $stats['card_sales'] = (float)db_fetch_value("
        SELECT COALESCE(SUM(total_amount), 0) FROM pos_sales 
        WHERE DATE(sale_time) = CURDATE()
        AND payment_status = 'completed'
        AND payment_method = 'card'
    ") ?: 0;
    
    $stats['mobile_sales'] = (float)db_fetch_value("
        SELECT COALESCE(SUM(total_amount), 0) FROM pos_sales 
        WHERE DATE(sale_time) = CURDATE()
        AND payment_status = 'completed'
        AND payment_method = 'mobile'
    ") ?: 0;
    
    $stats['room_charge_sales'] = (float)db_fetch_value("
        SELECT COALESCE(SUM(total_amount), 0) FROM pos_sales 
        WHERE DATE(sale_time) = CURDATE()
        AND payment_status = 'completed'
        AND payment_method = 'room'
    ") ?: 0;
    
} catch (Exception $e) {
    error_log("Error fetching POS stats: " . $e->getMessage());
}

// Calculate average ticket
$stats['avg_ticket'] = $stats['transactions_today'] > 0 
    ? $stats['sales_today'] / $stats['transactions_today'] 
    : 0;

// Get sales by outlet
$outlet_sales = [];
try {
    $outlet_sales = db_fetch_all("
        SELECT 
            o.outlet_id, o.outlet_name, o.outlet_code,
            COUNT(s.sale_id) as transactions,
            COALESCE(SUM(s.total_amount), 0) as revenue
        FROM pos_outlets o
        LEFT JOIN pos_sales s ON o.outlet_id = s.outlet_id 
            AND DATE(s.sale_time) = CURDATE()
            AND s.payment_status = 'completed'
        GROUP BY o.outlet_id
        ORDER BY revenue DESC
    ") ?: [];
} catch (Exception $e) {
    error_log("Error fetching outlet sales: " . $e->getMessage());
}

// Get top selling products
$top_products = [];
try {
    $top_products = db_fetch_all("
        SELECT 
            p.product_id, p.product_name, p.product_code,
            c.category_name,
            SUM(si.quantity) as quantity,
            SUM(si.total_amount) as revenue
        FROM pos_sale_items si
        JOIN pos_products p ON si.product_id = p.product_id
        LEFT JOIN pos_categories c ON p.category_id = c.category_id
        JOIN pos_sales s ON si.sale_id = s.sale_id
        WHERE DATE(s.sale_time) = CURDATE()
        AND s.payment_status = 'completed'
        GROUP BY p.product_id
        ORDER BY quantity DESC
        LIMIT 10
    ") ?: [];
} catch (Exception $e) {
    error_log("Error fetching top products: " . $e->getMessage());
}

// Get hourly sales
$hourly_sales = ['labels' => [], 'data' => []];
try {
    for ($hour = 0; $hour < 24; $hour++) {
        $hourly_sales['labels'][] = sprintf('%02d:00', $hour);
        $hourly_sales['data'][] = (float)db_fetch_value("
            SELECT COALESCE(SUM(total_amount), 0) FROM pos_sales 
            WHERE DATE(sale_time) = CURDATE()
            AND HOUR(sale_time) = ?
            AND payment_status = 'completed'
        ", [$hour]) ?: 0;
    }
} catch (Exception $e) {
    error_log("Error fetching hourly sales: " . $e->getMessage());
}

// Get recent transactions
$recent_sales = [];
try {
    $recent_sales = db_fetch_all("
        SELECT 
            s.*,
            u.first_name, u.last_name,
            o.outlet_name
        FROM pos_sales s
        LEFT JOIN users u ON s.user_id = u.user_id
        LEFT JOIN pos_outlets o ON s.outlet_id = o.outlet_id
        WHERE s.payment_status = 'completed'
        ORDER BY s.sale_time DESC
        LIMIT 15
    ") ?: [];
} catch (Exception $e) {
    error_log("Error fetching recent sales: " . $e->getMessage());
}

// Get low stock alerts
$low_stock = [];
try {
    $low_stock = db_fetch_all("
        SELECT 
            p.product_id, p.product_name, p.product_code,
            p.current_stock, p.min_stock,
            c.category_name
        FROM pos_products p
        LEFT JOIN pos_categories c ON p.category_id = c.category_id
        WHERE p.stock_item = 1
        AND p.current_stock <= p.min_stock
        ORDER BY (p.current_stock / NULLIF(p.min_stock, 0)) ASC
        LIMIT 10
    ") ?: [];
} catch (Exception $e) {
    error_log("Error fetching low stock: " . $e->getMessage());
}

// Get cashier performance
$cashier_performance = [];
try {
    $cashier_performance = db_fetch_all("
        SELECT 
            u.user_id, u.first_name, u.last_name,
            COUNT(s.sale_id) as transactions,
            COALESCE(SUM(s.total_amount), 0) as revenue,
            AVG(s.total_amount) as avg_ticket
        FROM users u
        LEFT JOIN pos_sales s ON u.user_id = s.user_id 
            AND DATE(s.sale_time) = CURDATE()
            AND s.payment_status = 'completed'
        WHERE u.is_active = 1
        GROUP BY u.user_id
        ORDER BY revenue DESC
        LIMIT 10
    ") ?: [];
} catch (Exception $e) {
    error_log("Error fetching cashier performance: " . $e->getMessage());
}

// Include header
$header_path = BASE_PATH . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>POS Dashboard</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
            .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
            .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
            .small-box { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; position: relative; overflow: hidden; color: #fff; }
            .small-box .inner { padding: 20px; }
            .small-box h3 { font-size: 2rem; font-weight: 700; margin: 0 0 10px 0; }
            .small-box p { font-size: 1rem; margin: 0; }
            .small-box .icon { position: absolute; top: 10px; right: 15px; font-size: 4rem; opacity: 0.3; }
            .small-box-footer { display: block; padding: 10px; text-align: center; background: rgba(0,0,0,0.1); color: #fff; text-decoration: none; }
            .bg-success { background-color: #28a745 !important; }
            .bg-info { background-color: #17a2b8 !important; }
            .bg-warning { background-color: #ffc107 !important; color: #000; }
            .bg-danger { background-color: #dc3545 !important; }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">POS Dashboard</a>
                    <div class="navbar-nav ms-auto">
                        <span class="nav-item nav-link text-white">
                            <i class="fas fa-user"></i> <?php echo htmlspecialchars($current_user['username'] ?? 'User'); ?>
                        </span>
                        <a class="nav-item nav-link" href="/HMSPOS/public/logout.php">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </div>
                </div>
            </nav>
            <div class="content-wrapper">
    <?php
}
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">POS Dashboard</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                    <li class="breadcrumb-item active">POS Dashboard</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Quick Actions -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card card-outline card-primary">
                    <div class="card-header">
                        <h3 class="card-title">Quick Actions</h3>
                    </div>
                    <div class="card-body">
                        <a href="/HMSPOS/pos/sales/pos.php" class="btn btn-primary mr-2 mb-2">
                            <i class="fas fa-cash-register mr-1"></i> Open POS Terminal
                        </a>
                        
                        <?php if (!$stats['my_shift']): ?>
                            <a href="/HMSPOS/pos/shifts/open.php" class="btn btn-success mr-2 mb-2">
                                <i class="fas fa-play mr-1"></i> Open Shift
                            </a>
                        <?php else: ?>
                            <a href="/HMSPOS/pos/shifts/close.php?id=<?php echo $stats['my_shift']; ?>" class="btn btn-warning mr-2 mb-2">
                                <i class="fas fa-stop mr-1"></i> Close Shift
                            </a>
                        <?php endif; ?>
                        
                        <a href="/HMSPOS/pos/sales/index.php" class="btn btn-info mr-2 mb-2">
                            <i class="fas fa-history mr-1"></i> Sales History
                        </a>
                        
                        <a href="/HMSPOS/pos/products/index.php" class="btn btn-secondary mr-2 mb-2">
                            <i class="fas fa-box mr-1"></i> Manage Products
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- Shift Status Alert -->
        <?php if (!$stats['my_shift'] && $stats['active_shifts'] > 0): ?>
            <div class="alert alert-info">
                <i class="fas fa-info-circle mr-2"></i>
                <strong><?php echo $stats['active_shifts']; ?> active shift(s)</strong> - You don't have an open shift. 
                <a href="/HMSPOS/pos/shifts/open.php" class="alert-link">Open a shift</a> to start selling.
            </div>
        <?php endif; ?>

        <!-- Stats Cards -->
        <div class="row">
            <div class="col-lg-3 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo function_exists('format_currency') ? format_currency($stats['sales_today']) : 'RWF ' . number_format($stats['sales_today']); ?></h3>
                        <p>Today's Sales</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-dollar-sign"></i>
                    </div>
                    <div class="small-box-footer">
                        vs Yesterday: 
                        <?php 
                        $change = $stats['sales_yesterday'] > 0 ? round((($stats['sales_today'] - $stats['sales_yesterday']) / $stats['sales_yesterday']) * 100, 1) : 0;
                        $change_class = $change >= 0 ? 'text-success' : 'text-danger';
                        ?>
                        <span class="<?php echo $change_class; ?>"><?php echo ($change >= 0 ? '+' : '') . $change; ?>%</span>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3><?php echo $stats['transactions_today']; ?></h3>
                        <p>Transactions Today</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-receipt"></i>
                    </div>
                    <div class="small-box-footer">
                        Avg: <?php echo function_exists('format_currency') ? format_currency($stats['avg_ticket']) : 'RWF ' . number_format($stats['avg_ticket']); ?>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo $stats['items_sold_today']; ?></h3>
                        <p>Items Sold</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-boxes"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo $stats['active_shifts']; ?></h3>
                        <p>Active Shifts</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-clock"></i>
                    </div>
                    <a href="/HMSPOS/pos/shifts/index.php" class="small-box-footer">View Shifts</a>
                </div>
            </div>
        </div>

        <!-- Payment Methods & Outlet Performance -->
        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Payment Methods (Today)</h3>
                    </div>
                    <div class="card-body">
                        <ul class="list-group">
                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                Cash
                                <span class="badge bg-success"><?php echo function_exists('format_currency') ? format_currency($stats['cash_sales']) : 'RWF ' . number_format($stats['cash_sales']); ?></span>
                            </li>
                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                Card
                                <span class="badge bg-info"><?php echo function_exists('format_currency') ? format_currency($stats['card_sales']) : 'RWF ' . number_format($stats['card_sales']); ?></span>
                            </li>
                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                Mobile Money
                                <span class="badge bg-warning"><?php echo function_exists('format_currency') ? format_currency($stats['mobile_sales']) : 'RWF ' . number_format($stats['mobile_sales']); ?></span>
                            </li>
                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                Room Charge
                                <span class="badge bg-primary"><?php echo function_exists('format_currency') ? format_currency($stats['room_charge_sales']) : 'RWF ' . number_format($stats['room_charge_sales']); ?></span>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>

            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Outlet Performance (Today)</h3>
                    </div>
                    <div class="card-body p-0">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>Outlet</th>
                                    <th class="text-center">Transactions</th>
                                    <th class="text-right">Revenue</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($outlet_sales)): ?>
                                    <tr><td colspan="3" class="text-center text-muted py-3">No data</td></tr>
                                <?php else: ?>
                                    <?php foreach ($outlet_sales as $outlet): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($outlet['outlet_name'] ?? 'Unknown'); ?></td>
                                        <td class="text-center"><?php echo $outlet['transactions'] ?? 0; ?></td>
                                        <td class="text-right"><?php echo function_exists('format_currency') ? format_currency($outlet['revenue'] ?? 0) : 'RWF ' . number_format($outlet['revenue'] ?? 0); ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Recent Transactions -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Recent Transactions</h3>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($recent_sales)): ?>
                            <div class="text-center text-muted py-4">No recent transactions</div>
                        <?php else: ?>
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Time</th>
                                        <th>Receipt</th>
                                        <th>Outlet</th>
                                        <th>Cashier</th>
                                        <th class="text-right">Amount</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($recent_sales as $sale): ?>
                                    <tr>
                                        <td><?php echo date('H:i', strtotime($sale['sale_time'] ?? 'now')); ?></td>
                                        <td><?php echo htmlspecialchars($sale['receipt_number'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars($sale['outlet_name'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars($sale['first_name'] ?? ''); ?></td>
                                        <td class="text-right"><?php echo function_exists('format_currency') ? format_currency($sale['total_amount'] ?? 0) : 'RWF ' . number_format($sale['total_amount'] ?? 0); ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Low Stock Alerts -->
        <div class="row">
            <div class="col-12">
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">Low Stock Alerts</h3>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($low_stock)): ?>
                            <div class="text-center text-muted py-4">No low stock items</div>
                        <?php else: ?>
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Product</th>
                                        <th>Category</th>
                                        <th class="text-center">Stock</th>
                                        <th class="text-center">Min</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($low_stock as $item): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($item['product_name'] ?? ''); ?></td>
                                        <td><?php echo htmlspecialchars($item['category_name'] ?? ''); ?></td>
                                        <td class="text-center"><?php echo $item['current_stock'] ?? 0; ?></td>
                                        <td class="text-center"><?php echo $item['min_stock'] ?? 0; ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<style>
.mr-1 { margin-right: 0.25rem; }
.mr-2 { margin-right: 0.5rem; }
.mb-2 { margin-bottom: 0.5rem; }
.mb-4 { margin-bottom: 1.5rem; }
.text-right { text-align: right; }
</style>

<?php
$footer_path = BASE_PATH . '/views/partials/footer.php';
if (file_exists($footer_path)) {
    require_once $footer_path;
} else {
    echo '</div></div></body></html>';
}
?>