<?php
/**
 * Dashboard Controller
 * Main dashboard and home page
 * 
 * @package RashwansBarber
 * @version 1.0
 */

class DashboardController extends Controller {
    
    public function __construct() {
        parent::__construct();
    }
    
    /**
     * Dashboard home page
     */
    public function index() {
        $this->requireLogin();
        
        $user = $this->getCurrentUser();
        $locationId = $user['location_id'];
        $roleId = $user['role_id'];
        
        // Get today's statistics
        $stats = $this->getTodayStats($locationId, $roleId);
        
        // Get recent transactions
        $recentTransactions = $this->getRecentTransactions($locationId, $roleId);
        
        // Get top barbers today
        $topBarbers = $this->getTopBarbers($locationId, $roleId);
        
        $data = [
            'title' => 'Dashboard - ' . config('app_name'),
            'user' => $user,
            'stats' => $stats,
            'recentTransactions' => $recentTransactions,
            'topBarbers' => $topBarbers
        ];
        
        $this->view('dashboard/index', $data);
    }
    
    /**
     * Get today's statistics
     * 
     * @param int $locationId Location ID (null for admin - all locations)
     * @param int $roleId Role ID
     * @return array
     */
    private function getTodayStats($locationId, $roleId) {
        $today = date('Y-m-d');
        
        // Base query
        $sql = "SELECT 
                    COUNT(t.transaction_id) as transaction_count,
                    COALESCE(SUM(t.total_amount), 0) as total_sales,
                    COALESCE(SUM(t.vat_amount), 0) as total_vat,
                    COALESCE(SUM(CASE WHEN p.payment_method = 'cash' THEN p.amount ELSE 0 END), 0) as cash_sales,
                    COALESCE(SUM(CASE WHEN p.payment_method = 'card' THEN p.amount ELSE 0 END), 0) as card_sales,
                    COUNT(DISTINCT t.barber_id) as active_barbers
                FROM transactions t
                LEFT JOIN payments p ON t.transaction_id = p.transaction_id
                WHERE DATE(t.transaction_date) = ? 
                AND t.status = 'completed'";
        
        $params = [$today];
        
        // Filter by location for cashiers
        if ($roleId == 2 && $locationId) {
            $sql .= " AND t.location_id = ?";
            $params[] = $locationId;
        }
        
        $stats = $this->db->fetchOne($sql, $params);
        
        // Get yesterday's sales for comparison
        $yesterday = date('Y-m-d', strtotime('-1 day'));
        $sqlYesterday = str_replace('DATE(t.transaction_date) = ?', 'DATE(t.transaction_date) = ?', $sql);
        $params[0] = $yesterday;
        
        $yesterdayStats = $this->db->fetchOne($sqlYesterday, $params);
        
        // Calculate percentage change
        $stats['sales_change'] = 0;
        if ($yesterdayStats['total_sales'] > 0) {
            $stats['sales_change'] = (($stats['total_sales'] - $yesterdayStats['total_sales']) / $yesterdayStats['total_sales']) * 100;
        }
        
        return $stats;
    }
    
    /**
     * Get recent transactions
     * 
     * @param int $locationId Location ID
     * @param int $roleId Role ID
     * @return array
     */
    private function getRecentTransactions($locationId, $roleId, $limit = 10) {
        $sql = "SELECT 
                    t.transaction_id,
                    t.receipt_number,
                    t.transaction_date,
                    t.total_amount,
                    t.status,
                    b.full_name as barber_name,
                    l.location_name,
                    u.full_name as cashier_name
                FROM transactions t
                JOIN barbers b ON t.barber_id = b.barber_id
                JOIN locations l ON t.location_id = l.location_id
                JOIN users u ON t.cashier_id = u.user_id
                WHERE 1=1";
        
        $params = [];
        
        // Filter by location for cashiers
        if ($roleId == 2 && $locationId) {
            $sql .= " AND t.location_id = ?";
            $params[] = $locationId;
        }
        
        $sql .= " ORDER BY t.transaction_date DESC LIMIT ?";
        $params[] = $limit;
        
        return $this->db->fetchAll($sql, $params);
    }
    
    /**
     * Get top performing barbers today
     * 
     * @param int $locationId Location ID
     * @param int $roleId Role ID
     * @return array
     */
    private function getTopBarbers($locationId, $roleId, $limit = 5) {
        $today = date('Y-m-d');
        
        $sql = "SELECT 
                    b.barber_id,
                    b.full_name,
                    b.employee_id,
                    COUNT(t.transaction_id) as transaction_count,
                    COALESCE(SUM(t.total_amount), 0) as total_sales,
                    COALESCE(SUM(ti.commission_amount), 0) as total_commission
                FROM barbers b
                LEFT JOIN transactions t ON b.barber_id = t.barber_id 
                    AND DATE(t.transaction_date) = ? 
                    AND t.status = 'completed'
                LEFT JOIN transaction_items ti ON t.transaction_id = ti.transaction_id
                WHERE b.status = 'active'";
        
        $params = [$today];
        
        // Filter by location for cashiers
        if ($roleId == 2 && $locationId) {
            $sql .= " AND EXISTS (
                        SELECT 1 FROM barber_locations bl 
                        WHERE bl.barber_id = b.barber_id 
                        AND bl.location_id = ?
                      )";
            $params[] = $locationId;
        }
        
        $sql .= " GROUP BY b.barber_id, b.full_name, b.employee_id
                  ORDER BY total_sales DESC 
                  LIMIT ?";
        $params[] = $limit;
        
        return $this->db->fetchAll($sql, $params);
    }
}
?>