<?php
require_once __DIR__.'/../../../includes/auth.php';
requireLogin();
requirePermission('view_billing');

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

/* LOAD CUSTOMERS */
$customers = $pdo->query("
SELECT id, customer_name 
FROM billing_customers
ORDER BY customer_name
")->fetchAll(PDO::FETCH_ASSOC);

/* SAVE ACCOUNT */
if($_SERVER['REQUEST_METHOD'] === 'POST'){

    $customerId = $_POST['customer_id'];
    $accountName = trim($_POST['account_name']);
    $municipality = trim($_POST['municipality_name']);

    if(!$customerId || $accountName === ''){
        $error = "All fields are required.";
    } else {

        $stmt = $pdo->prepare("
        INSERT INTO billing_accounts (customer_id, account_name, municipality_name)
        VALUES (?,?,?)
        ");
        $stmt->execute([$customerId, $accountName, $municipality]);

        $success = "Account created successfully.";
    }
}
?>

<div class="container">

<div class="page-header">
<h2>Add Account / Property</h2>
</div>

<?php if(isset($error)): ?>
<div style="background:#f8d7da;padding:10px;margin-bottom:10px;">
<?= $error ?>
</div>
<?php endif; ?>

<?php if(isset($success)): ?>
<div style="background:#d4edda;padding:10px;margin-bottom:10px;">
<?= $success ?>
</div>
<?php endif; ?>

<div class="stat-card">

<form method="POST">

<label>Customer</label>
<select name="customer_id" required>
<option value="">Select Customer</option>

<?php foreach($customers as $c): ?>
<option value="<?= $c['id'] ?>">
<?= htmlspecialchars($c['customer_name']) ?>
</option>
<?php endforeach; ?>

</select>

<br><br>

<label>Account / Property Name</label>
<input type="text" name="account_name" required>

<br><br>

<label>Municipality</label>
<input type="text" name="municipality_name">

<br><br>

<button class="btn btn-primary">Save Account</button>

</form>

</div>

</div>

<?php require_once __DIR__.'/../../../includes/layout_footer.php'; ?>