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

        $tid = Auth::tenantId();
        
        // Get customers with due balances
        $customers = CustomerLedger::getCustomersWithDueBalance();
        
        $pageTitle = 'Customer Ledger';
        ob_start();
        include APP_ROOT . '/views/tenant/ledger/customer-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']);

        $customerId = (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 = CustomerLedger::getCustomerLedger($customerId, $page, $filters);
        $summary = CustomerLedger::getCustomerSummary($customerId);
        
        // Get customer details
        $customer = db()->prepare("SELECT * FROM customers WHERE id = ? AND tenant_id = ?");
        $customer->execute([$customerId, Auth::tenantId()]);
        $customer = $customer->fetch();

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

        $pageTitle = 'Customer Ledger: ' . e($customer['name']);
        ob_start();
        include APP_ROOT . '/views/tenant/ledger/customer-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 customers
        $customers = db()->prepare("SELECT * FROM customers WHERE tenant_id = ? ORDER BY name");
        $customers->execute([$tid]);
        $customers = $customers->fetchAll();

        $pageTitle = 'Add Ledger Entry';
        ob_start();
        include APP_ROOT . '/views/tenant/ledger/customer-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 = [
                'customer_id' => (int)$_POST['customer_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();
            }

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

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

        try {
            $data = [
                'customer_id' => (int)$_POST['customer_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();
            }

            CustomerLedger::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']);

        $customerId = (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 = CustomerLedger::getCustomerLedger($customerId, 1, $filters, 9999);
        $summary = CustomerLedger::getCustomerSummary($customerId);
        
        // Get customer details
        $customer = db()->prepare("SELECT * FROM customers WHERE id = ? AND tenant_id = ?");
        $customer->execute([$customerId, Auth::tenantId()]);
        $customer = $customer->fetch();

        if (!$customer) {
            echo 'Customer not found';
            return;
        }

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