<?php
ini_set('display_errors',1);
error_reporting(E_ALL);

require_once __DIR__.'/../../../includes/auth.php';
requireLogin();
requirePermission('view_statements');

require_once __DIR__.'/../../../config/database.php';
require_once __DIR__.'/../../../includes/layout.php';

/* ===============================
LOAD ACCOUNTS
================================ */
$search = $_GET['search'] ?? '';

$sql = "
SELECT 
    ba.id,
    ba.account_name,
    cu.customer_name
FROM billing_accounts ba
LEFT JOIN billing_customers cu ON cu.id = ba.customer_id
";

$params = [];

if($search){
    $sql .= " WHERE cu.customer_name LIKE ? OR ba.account_name LIKE ?";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$sql .= " ORDER BY cu.customer_name ASC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$accounts = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>

<h2>Statements</h2>


<form method="GET" style="margin-bottom:15px; display:flex; gap:10px;">

    <input type="text" name="search" placeholder="Search customer or account..."
           value="<?= htmlspecialchars($_GET['search'] ?? '') ?>"
           class="form-control" style="max-width:300px;">

    <button type="submit" class="btn btn-primary">Search</button>

    <a href="index.php" class="btn btn-secondary">Reset</a>

</form>

<div class="card">
    <div class="card-body">

        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>Customer</th>
                    <th>Account</th>
                    <th>Action</th>
                </tr>
            </thead>

            <tbody>
                <?php if(!empty($accounts)): ?>
                    <?php foreach($accounts as $acc): ?>
                    <tr>
                        <td><?= htmlspecialchars($acc['customer_name'] ?? '') ?></td>
                        <td><?= htmlspecialchars($acc['account_name']) ?></td>
                        <td>
                            <a href="view.php?account_id=<?= $acc['id'] ?>" class="btn btn-primary btn-sm">
                                View Statement
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="3" style="text-align:center;">
                            No accounts found
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>

        </table>

    </div>
</div>