<?php
class SupplierLedgerController {
    
    public function index(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Auth::requireRole(['admin','owner','manager']);

        $tid = Auth::tenantId();
        
        // Get suppliers with due balances
        $suppliers = SupplierLedger::getSuppliersWithDueBalance();
        
        $pageTitle = 'Supplier Ledger';
        ob_start();
        include APP_ROOT . '/views/tenant/ledger/supplier-index.php';
        $content = ob_get_clean();
        include APP_ROOT . '/views/tenant/layouts/main.php';
    }

    public function show(string $id): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Auth::requireRole(['admin','owner','manager']);

        $supplierId = (int)$id;
        $page = (int)($_GET['page'] ?? 1);
        
        $filters = [
            'date_from' => $_GET['date_from'] ?? date('Y-m-01'),
            'date_to' => $_GET['date_to'] ?? date('Y-m-d'),
            'transaction_type' => $_GET['transaction_type'] ?? ''
        ];

        $ledger = SupplierLedger::getSupplierLedger($supplierId, $page, $filters);
        $summary = SupplierLedger::getSupplierSummary($supplierId);
        
        // Get supplier details
        $supplier = db()->prepare("SELECT * FROM suppliers WHERE id = ? AND tenant_id = ?");
        $supplier->execute([$supplierId, Auth::tenantId()]);
        $supplier = $supplier->fetch();

        if (!$supplier) {
            flash('error', 'Supplier not found');
            redirect('supplier-ledger');
        }

        $pageTitle = 'Supplier Ledger: ' . e($supplier['name']);
        ob_start();
        include APP_ROOT . '/views/tenant/ledger/supplier-show.php';
        $content = ob_get_clean();
        include APP_ROOT . '/views/tenant/layouts/main.php';
    }

    public function create(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Auth::requireRole(['admin','owner','manager']);

        $tid = Auth::tenantId();
        
        // Get all suppliers
        $suppliers = db()->prepare("SELECT * FROM suppliers WHERE tenant_id = ? ORDER BY name");
        $suppliers->execute([$tid]);
        $suppliers = $suppliers->fetchAll();

        $pageTitle = 'Add Ledger Entry';
        ob_start();
        include APP_ROOT . '/views/tenant/ledger/supplier-create.php';
        $content = ob_get_clean();
        include APP_ROOT . '/views/tenant/layouts/main.php';
    }

    public function store(): void {
        Auth::requireLogin();
        Security::checkCsrf();
        Auth::requireRole(['admin','owner','manager']);

        try {
            $data = [
                'supplier_id' => (int)$_POST['supplier_id'],
                'transaction_type' => $_POST['transaction_type'],
                'reference_id' => !empty($_POST['reference_id']) ? (int)$_POST['reference_id'] : null,
                'reference_no' => $_POST['reference_no'] ?? null,
                'debit' => (float)($_POST['debit'] ?? 0),
                'credit' => (float)($_POST['credit'] ?? 0),
                'description' => $_POST['description'] ?? null,
                'transaction_date' => $_POST['transaction_date'] ?? date('Y-m-d')
            ];

            if ($data['debit'] <= 0 && $data['credit'] <= 0) {
                flash('error', 'Please enter either debit or credit amount');
                redirectBack();
            }

            SupplierLedger::addEntry($data);
            flash('success', 'Ledger entry added successfully');
            redirect('supplier-ledger/' . $data['supplier_id']);
        } catch (Exception $e) {
            flash('error', 'Error adding ledger entry: ' . $e->getMessage());
            redirectBack();
        }
    }

    public function addOpeningBalance(): void {
        Auth::requireLogin();
        Security::checkCsrf();
        Auth::requirePermission('purchases.view');

        try {
            $data = [
                'supplier_id' => (int)$_POST['supplier_id'],
                'transaction_type' => 'opening_balance',
                'debit' => (float)$_POST['opening_balance'],
                'credit' => 0,
                'description' => 'Opening balance',
                'transaction_date' => $_POST['transaction_date'] ?? date('Y-m-d')
            ];

            if ($data['debit'] <= 0) {
                flash('error', 'Opening balance must be greater than 0');
                redirectBack();
            }

            SupplierLedger::addEntry($data);
            flash('success', 'Opening balance added successfully');
            redirectBack();
        } catch (Exception $e) {
            flash('error', 'Error adding opening balance: ' . $e->getMessage());
            redirectBack();
        }
    }

    public function print(string $id, string $format = 'a4'): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Auth::requireRole(['admin','owner','manager']);

        $supplierId = (int)$id;
        
        // Get filter from query params
        $filters = [
            'date_from' => $_GET['date_from'] ?? date('Y-m-01'),
            'date_to' => $_GET['date_to'] ?? date('Y-m-d'),
            'transaction_type' => $_GET['transaction_type'] ?? ''
        ];

        $ledger = SupplierLedger::getSupplierLedger($supplierId, 1, $filters, 9999);
        $summary = SupplierLedger::getSupplierSummary($supplierId);
        
        // Get supplier details
        $supplier = db()->prepare("SELECT * FROM suppliers WHERE id = ? AND tenant_id = ?");
        $supplier->execute([$supplierId, Auth::tenantId()]);
        $supplier = $supplier->fetch();

        if (!$supplier) {
            echo 'Supplier not found';
            return;
        }

        $tenant = Auth::tenant();
        
        ob_start();
        include APP_ROOT . '/views/tenant/ledger/supplier-print.php';
        $content = ob_get_clean();
        echo $content;
    }
}
