<?php
declare(strict_types=1);

namespace App\Modules\Sales\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Inventory\Models\Warehouse;

class SaleReportController extends Controller
{
    public function daily(Request $request): Response
    {
        $db = App::getInstance()->db();
        $date = trim((string) $request->get('date', date('Y-m-d')));
        $warehouseId = (int) $request->get('warehouse_id', 0);

        $where = 's.`sale_date` = ? AND s.`status` != ?';
        $params = [$date, 'voided'];

        if ($warehouseId > 0) {
            $where .= ' AND s.`warehouse_id` = ?';
            $params[] = $warehouseId;
        }

        $summary = $db->selectOne(
            "SELECT COUNT(*) as sale_count,
                    COALESCE(SUM(s.`total_amount`), 0) as total_revenue,
                    COALESCE(SUM(s.`discount_amount`), 0) as total_discounts,
                    COALESCE(SUM(s.`tax_amount`), 0) as total_tax,
                    COALESCE(SUM(s.`amount_refunded`), 0) as total_refunds
             FROM `sales` s
             WHERE {$where}",
            $params
        );

        $sales = $db->select(
            "SELECT s.*, w.`name_ar` as warehouse_name
             FROM `sales` s
             JOIN `warehouses` w ON w.`id` = s.`warehouse_id`
             WHERE {$where}
             ORDER BY s.`created_at` DESC",
            $params
        );

        $byMethod = $db->select(
            "SELECT s.`payment_method`, COUNT(*) as cnt, SUM(s.`total_amount`) as total
             FROM `sales` s
             WHERE {$where}
             GROUP BY s.`payment_method`",
            $params
        );

        return $this->view('Sales.Views.reports.daily', [
            'summary'     => $summary,
            'sales'       => $sales,
            'byMethod'    => $byMethod,
            'date'        => $date,
            'warehouses'  => Warehouse::allActive(),
            'warehouseId' => $warehouseId,
        ]);
    }

    public function monthly(Request $request): Response
    {
        $db = App::getInstance()->db();
        $month = trim((string) $request->get('month', date('Y-m')));
        $warehouseId = (int) $request->get('warehouse_id', 0);

        $dateFrom = $month . '-01';
        $dateTo = date('Y-m-t', strtotime($dateFrom));

        $where = 's.`sale_date` BETWEEN ? AND ? AND s.`status` != ?';
        $params = [$dateFrom, $dateTo, 'voided'];

        if ($warehouseId > 0) {
            $where .= ' AND s.`warehouse_id` = ?';
            $params[] = $warehouseId;
        }

        $summary = $db->selectOne(
            "SELECT COUNT(*) as sale_count,
                    COALESCE(SUM(s.`total_amount`), 0) as total_revenue,
                    COALESCE(SUM(s.`discount_amount`), 0) as total_discounts,
                    COALESCE(SUM(s.`tax_amount`), 0) as total_tax,
                    COALESCE(SUM(s.`amount_refunded`), 0) as total_refunds
             FROM `sales` s
             WHERE {$where}",
            $params
        );

        $dailyBreakdown = $db->select(
            "SELECT s.`sale_date`, COUNT(*) as cnt,
                    SUM(s.`total_amount`) as total,
                    SUM(s.`amount_refunded`) as refunded
             FROM `sales` s
             WHERE {$where}
             GROUP BY s.`sale_date`
             ORDER BY s.`sale_date` ASC",
            $params
        );

        return $this->view('Sales.Views.reports.monthly', [
            'summary'        => $summary,
            'dailyBreakdown' => $dailyBreakdown,
            'month'          => $month,
            'warehouses'     => Warehouse::allActive(),
            'warehouseId'    => $warehouseId,
        ]);
    }

    public function byItem(Request $request): Response
    {
        $db = App::getInstance()->db();
        $dateFrom = trim((string) $request->get('date_from', date('Y-m-01')));
        $dateTo   = trim((string) $request->get('date_to', date('Y-m-d')));

        $rows = $db->select(
            "SELECT si.`item_name_ar`,
                    COALESCE(i.`sku`, '—') as sku,
                    SUM(si.`quantity`) as total_qty,
                    SUM(si.`line_total`) as total_revenue,
                    SUM(si.`quantity` * COALESCE(si.`cost_price`, 0)) as total_cost,
                    SUM(si.`line_total`) - SUM(si.`quantity` * COALESCE(si.`cost_price`, 0)) as profit
             FROM `sale_items` si
             JOIN `sales` s ON s.`id` = si.`sale_id`
             LEFT JOIN `inventory_items` i ON i.`id` = si.`item_id`
             WHERE s.`sale_date` BETWEEN ? AND ?
               AND s.`status` != 'voided'
             GROUP BY si.`item_name_ar`, i.`sku`
             ORDER BY total_revenue DESC",
            [$dateFrom, $dateTo]
        );

        return $this->view('Sales.Views.reports.by_item', [
            'rows'     => $rows,
            'dateFrom' => $dateFrom,
            'dateTo'   => $dateTo,
        ]);
    }
}
