<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Response;
use App\Models\ReportModel;
use App\Helpers\ExportHelper;

class ReportController extends Controller
{
    private ReportModel $reportModel;

    public function __construct()
    {
        $this->reportModel = new ReportModel();
    }

    public function salesSummary(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $from = $_GET['from'] ?? date('Y-m-01');
        $to = $_GET['to'] ?? date('Y-m-t');
        $groupBy = $_GET['group_by'] ?? 'monthly';

        $data = $this->reportModel->getSalesSummary($tenantId, $from, $to, $groupBy);
        Response::success($data);
    }

    public function purchaseSummary(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $from = $_GET['from'] ?? date('Y-m-01');
        $to = $_GET['to'] ?? date('Y-m-t');
        $groupBy = $_GET['group_by'] ?? 'monthly';

        $data = $this->reportModel->getPurchaseSummary($tenantId, $from, $to, $groupBy);
        Response::success($data);
    }

    public function profitLoss(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $from = $_GET['from'] ?? date('Y-m-01');
        $to = $_GET['to'] ?? date('Y-m-t');

        $data = $this->reportModel->getProfitLoss($tenantId, $from, $to);
        Response::success($data);
    }

    public function receivablesAging(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $asOf = $_GET['as_of'] ?? date('Y-m-d');

        $data = $this->reportModel->getReceivablesAging($tenantId, $asOf);
        Response::success($data);
    }

    public function payablesAging(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $asOf = $_GET['as_of'] ?? date('Y-m-d');

        $data = $this->reportModel->getPayablesAging($tenantId, $asOf);
        Response::success($data);
    }

    public function cashFlow(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $from = $_GET['from'] ?? date('Y-m-01');
        $to = $_GET['to'] ?? date('Y-m-t');

        $data = $this->reportModel->getCashFlow($tenantId, $from, $to);
        Response::success($data);
    }

    public function stockSummary(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $asOf = $_GET['as_of'] ?? date('Y-m-d');
        $warehouseId = isset($_GET['warehouse_id']) ? (int)$_GET['warehouse_id'] : null;

        $data = $this->reportModel->getStockSummaryReport($tenantId, $asOf, $warehouseId);
        Response::success($data);
    }

    public function expenseSummary(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $from = $_GET['from'] ?? date('Y-m-01');
        $to = $_GET['to'] ?? date('Y-m-t');

        $data = $this->reportModel->getExpenseSummary($tenantId, $from, $to);
        Response::success($data);
    }

    public function taxSummary(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $from = $_GET['from'] ?? date('Y-m-01');
        $to = $_GET['to'] ?? date('Y-m-t');

        $data = $this->reportModel->getTaxSummary($tenantId, $from, $to);
        Response::success($data);
    }

    public function customerOutstanding(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $data = $this->reportModel->getCustomerOutstanding($tenantId);
        Response::success($data);
    }

    public function vendorOutstanding(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $data = $this->reportModel->getVendorOutstanding($tenantId);
        Response::success($data);
    }

    public function dayBook(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $date = $_GET['date'] ?? date('Y-m-d');
        $data = $this->reportModel->getDayBook($tenantId, $date);
        Response::success($data);
    }

    public function stockMovement(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        
        $filters = [
            'product_id' => isset($_GET['product_id']) && $_GET['product_id'] !== '' ? (int) $_GET['product_id'] : null,
            'warehouse_id' => isset($_GET['warehouse_id']) && $_GET['warehouse_id'] !== '' ? (int) $_GET['warehouse_id'] : null,
            'type' => $_GET['type'] ?? null,
            'from_date' => $_GET['from'] ?? null,
            'to_date' => $_GET['to'] ?? null
        ];

        $page = isset($_GET['page']) ? max(1, (int) $_GET['page']) : 1;
        $perPage = isset($_GET['per_page']) ? max(1, (int) $_GET['per_page']) : 10;

        $movements = $this->reportModel->getStockMovement($tenantId, $filters, $page, $perPage);
        $total = $this->reportModel->countStockMovements($tenantId, $filters);

        Response::success([
            'data' => $movements,
            'pagination' => [
                'current_page' => $page,
                'per_page' => $perPage,
                'total_records' => $total,
                'total_pages' => ceil($total / $perPage)
            ]
        ]);
    }

    public function export(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $reportType = $_GET['report'] ?? 'profit-loss';
        $format = $_GET['format'] ?? 'csv';
        $from = $_GET['from'] ?? date('Y-01-01'); // Year to date
        $to = $_GET['to'] ?? date('Y-m-d'); 

        $data = [];
        $headers = [];
        $title = ucfirst(str_replace(['-', '_'], ' ', $reportType));

        switch ($reportType) {
            case 'profit-loss':
                $res = $this->reportModel->getProfitLoss($tenantId, $from, $to);
                $headers = ['Section', 'Category', 'Amount'];
                $data = [
                    ['Income', 'Sales & Revenue', $res['income']['sales']],
                    ['Income', 'Total Income', $res['income']['total']],
                    ['Expense', 'Purchases/COGS', $res['expenses']['purchases']],
                    ['Expense', 'Operational Expenses', $res['expenses']['operational_expenses']],
                    ['Expense', 'Total Expenses', $res['expenses']['total']],
                    ['Summary', 'Gross Profit', $res['gross_profit']],
                    ['Summary', 'Net Profit', $res['net_profit']]
                ];
                break;

            case 'stock-summary':
                $res = $this->reportModel->getStockSummaryReport($tenantId, $to);
                $headers = ['Product Name', 'SKU', 'Unit', 'Stock Hand', 'Avg Cost', 'Stock Value'];
                foreach ($res as $row) {
                    $data[] = [
                        $row['name'], $row['sku'], $row['unit'], 
                        $row['closing_stock'], number_format((float)$row['avg_cost'], 2), 
                        number_format((float)$row['stock_value'], 2)
                    ];
                }
                break;

            case 'customer-outstanding':
                $res = $this->reportModel->getCustomerOutstanding($tenantId);
                $headers = ['Customer Name', 'Invoice Count', 'Total Outstanding'];
                foreach ($res as $row) {
                    $data[] = [$row['name'], $row['invoice_count'], number_format((float)$row['total_due'], 2)];
                }
                break;

            case 'sales-summary':
                $res = $this->reportModel->getSalesSummary($tenantId, $from, $to);
                $headers = ['Period', 'Total Amount', 'Tax Amount', 'Net Amount'];
                foreach ($res as $row) {
                    $data[] = [
                        $row['period'], 
                        number_format((float)$row['total_amount'], 2), 
                        number_format((float)$row['tax_amount'], 2), 
                        number_format((float)$row['net_amount'], 2)
                    ];
                }
                break;

            default:
                Response::error("Invalid report type for export");
                return;
        }

        $filename = "BillFlow_{$reportType}_" . date('Ymd');

        if ($format === 'csv') {
            ExportHelper::exportCSV($headers, $data, "{$filename}.csv");
        } elseif ($format === 'pdf') {
            $html = "
                <div style='font-family: Arial, sans-serif;'>
                    <h1 style='color: #0f172a; text-align: center;'>$title</h1>
                    <p style='text-align: center; color: #64748b; font-size: 12px;'>Generated on ".date('d-M-Y')." | Period: $from to $to</p>
                    <table border='1' cellspacing='0' cellpadding='8' width='100%' style='border-collapse: collapse; margin-top: 20px;'>
                        <thead style='background: #f8fafc;'>
                            <tr>";
            foreach ($headers as $h) {
                $html .= "<th style='text-align: left; font-size: 12px; color: #475569;'>$h</th>";
            }
            $html .= "</tr></thead><tbody>";
            foreach ($data as $row) {
                $html .= "<tr>";
                foreach ($row as $val) {
                    $html .= "<td style='font-size: 12px; color: #1e293b;'>$val</td>";
                }
                $html .= "</tr>";
            }
            $html .= "</tbody></table></div>";
            ExportHelper::exportPDF($html, "{$filename}.pdf");
        }
    }
}
