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

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

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

require_once __DIR__.'/../../../includes/header.php';
require_once __DIR__.'/../../../includes/sidebar.php';

$resultMessage = "";

/* Default billing dates */
$periodStart = $_POST['period_start'] ?? date('Y-m-01');
$periodEnd   = $_POST['period_end'] ?? date('Y-m-t');

?>

<div class="main-content">

<div class="page-header">
<h2>Billing Runs</h2>
</div>

<div class="stat-card">

<h3>Run Monthly Billing</h3>

<p>
This process will:
</p>

<ul>
<li>Calculate meter usage</li>
<li>Apply tariff blocks</li>
<li>Create invoices</li>
<li>Generate invoice lines</li>
</ul>

<form method="GET" action="billing_run.php">

<label>Billing Start</label><br>
<input type="date" name="period_start" value="<?= htmlspecialchars($periodStart) ?>" required>

<br><br>

<label>Billing End</label><br>
<input type="date" name="period_end" value="<?= htmlspecialchars($periodEnd) ?>" required>

<br><br>

<button type="submit" class="btn btn-primary">
⚡ Run Billing
</button>

</form>

</div>

<?php if($resultMessage): ?>

<div class="stat-card" style="margin-top:20px;">

<h3>Billing Result</h3>

<div style="background:#f4f6f8;padding:15px;border-radius:8px;">
<?php echo $resultMessage; ?>
</div>

</div>

<?php endif; ?>

</div>

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