<?php
/**
 * Dashboard Controller — Aggregated Statistics
 */

class DashboardController {
    private PDO $db;
    private object $user;

    public function __construct(PDO $db, object $user) {
        $this->db = $db;
        $this->user = $user;
    }

    /** GET /dashboard/stats */
    public function stats(): void {
        $today = date('Y-m-d');

        // Today's purchases
        $pStmt = $this->db->prepare("
            SELECT COUNT(*) as count, COALESCE(SUM(total_gross_amount), 0) as total
            FROM purchase_master WHERE voucher_date = ? AND is_reversed = 0
        ");

        $pStmt->execute([$today]);
        $purchases = $pStmt->fetch();

        // Today's sales
        $sStmt = $this->db->prepare("
            SELECT COUNT(*) as count, COALESCE(SUM(gross_amount), 0) as total
            FROM sale_master WHERE voucher_date = ? AND is_reversed = 0
        ");
        $sStmt->execute([$today]);
        $sales = $sStmt->fetch();

        // Active inventory lots
        $lotStmt = $this->db->query("SELECT COUNT(*) as count FROM purchase_lots WHERE status IN ('available', 'partial')");
        $lots = $lotStmt->fetch();

        // Cash in Hand balance (account with sub_type = 'cash')
        $cashStmt = $this->db->prepare("SELECT id FROM accounts WHERE is_system = 1 AND sub_type = 'cash' LIMIT 1");
        $cashStmt->execute();
        $cashAccId = (int)$cashStmt->fetchColumn();
        $cashBalance = $cashAccId ? AccountingService::getBalance($this->db, $cashAccId) : 0;

        // Total parties
        $partyStmt = $this->db->query("SELECT COUNT(*) as count FROM accounts WHERE type = 'party' AND is_active = 1");
        $parties = $partyStmt->fetch();

        // Due Alerts (Sales due today or earlier, or due tomorrow)
        // remaining_balance > 0 and due_date <= TOMORROW
        $alertsStmt = $this->db->prepare("
            SELECT sm.id, sm.voucher_no, sm.due_date, sm.remaining_balance, a.name as khareedar_name
            FROM sale_master sm
            JOIN accounts a ON sm.khareedar_id = a.id
            WHERE sm.is_reversed = 0 
              AND sm.remaining_balance > 0 
              AND sm.due_date IS NOT NULL 
              AND sm.due_date <= DATE_ADD(?, INTERVAL 2 DAY)
            ORDER BY sm.due_date ASC
        ");
        $alertsStmt->execute([$today]);
        $dueAlerts = $alertsStmt->fetchAll();

        // Account/Credit Card Alerts
        $accAlertsStmt = $this->db->prepare("
            SELECT id, name, alert_date, alert_interval_days
            FROM accounts
            WHERE is_active = 1
              AND alert_date IS NOT NULL
              AND alert_date <= DATE_ADD(?, INTERVAL 2 DAY)
            ORDER BY alert_date ASC
        ");
        $accAlertsStmt->execute([$today]);
        $accountAlerts = $accAlertsStmt->fetchAll();

        Response::success([
            'today_purchases' => [
                'count' => (int)$purchases['count'],
                'total' => floatval($purchases['total'])
            ],
            'today_sales' => [
                'count' => (int)$sales['count'],
                'total' => floatval($sales['total'])
            ],
            'inventory_lots' => (int)$lots['count'],
            'cash_in_hand' => $cashBalance,
            'total_parties' => (int)$parties['count'],
            'due_alerts' => $dueAlerts,
            'account_alerts' => $accountAlerts
        ]);
    }
}
