<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Models\Client;
use App\Models\ClientTransaction;
use Dompdf\Dompdf;
use Dompdf\Options;

class ClientPortalController extends Controller
{
    protected function requireClientAuth()
    {
        if (!isset($_SESSION['client_id'])) {
            $this->redirect('/client/login');
            exit;
        }
    }

    public function dashboard()
    {
        $this->requireClientAuth();
        $clientModel = new Client();
        $client = $clientModel->find($_SESSION['client_id']);
        if (!$client) {
            $this->redirect('/client/logout');
        }

        $transModel = new ClientTransaction();
        $recentTransactions = $transModel->getForClient($_SESSION['client_id']);

        $this->render('client/dashboard', [
            'pageTitle' => 'My Account',
            'client' => $client,
            'recentTransactions' => $recentTransactions ?? []
        ]);
    }

    public function transactions()
    {
        $this->requireClientAuth();

        // Date range from GET parameters (defaults to current month)
        $fromDate = $_GET['from'] ?? date('Y-m-01');
        $toDate   = $_GET['to'] ?? date('Y-m-t');

        $clientModel = new Client();
        $client = $clientModel->find($_SESSION['client_id']);
        if (!$client) {
            $this->redirect('/client/logout');
            return;
        }

        // Fetch combined statement (deposits + transactions)
        $statement = $clientModel->getStatement($client['id'], $fromDate, $toDate);

        $this->render('client/transactions', [
            'pageTitle' => 'My Transactions',
            'client'    => $client,
            'entries'   => $statement['entries'] ?? [],
            'fromDate'  => $fromDate,
            'toDate'    => $toDate
        ]);
    }

    public function statementPdf()
    {
        $this->requireClientAuth();
        $clientModel = new Client();
        $statement = $clientModel->getStatement(
            $_SESSION['client_id'],
            $_GET['from'] ?? null,
            $_GET['to'] ?? null
        );
        if (!$statement) {
            die("No data");
        }

        $html = $this->generateClientStatementHtml($statement);
        $options = new Options();
        $options->set('isHtml5ParserEnabled', true);
        $dompdf = new Dompdf($options);
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();
        $dompdf->stream('My_Statement_' . date('Ymd') . '.pdf', ['Attachment' => true]);
        exit;
    }

    private function generateClientStatementHtml(array $statement): string
    {
        ob_start();
        ?>
        <!DOCTYPE html>
        <html><head><meta charset="UTF-8"><style>
            body { font-family: DejaVu Sans; font-size: 12px; }
            table { width: 100%; border-collapse: collapse; }
            th, td { border: 1px solid #ddd; padding: 8px; }
            th { background: #f2f2f2; }
        </style></head><body>
        <h2>Statement for <?= htmlspecialchars($statement['client']['full_name']) ?></h2>
        <p>Balance: <?= number_format($statement['current_balance'], 2) ?></p>
        <table><thead><tr><th>Date</th><th>Type</th><th>Amount</th><th>Balance</th><th>Reference</th></tr></thead><tbody>
        <?php foreach ($statement['entries'] as $e): ?>
            <tr>
                <td><?= date('Y-m-d H:i', strtotime($e['date'])) ?></td>
                <td><?= $e['type'] ?></td>
                <td><?= number_format($e['amount'], 2) ?></td>
                <td><?= number_format($e['balance'], 2) ?></td>
                <td><?= htmlspecialchars($e['reference'] ?? '') ?></td>
            </tr>
        <?php endforeach; ?>
        </tbody></table></body></html>
        <?php
        return ob_get_clean();
    }
}