<?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');

/* STEP CONTROL */
$showStep2 = isset($_POST['run_billing']);

if(isset($_POST['run_billing'])){

    // Pass selected dates to billing engine
    $_POST['billing_period_start'] = $periodStart;
    $_POST['billing_period_end']   = $periodEnd;

    ob_start();

    require __DIR__.'/billing_run.php';

    $resultMessage = ob_get_clean();
}
?>

<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="POST">

<!-- STEP 1 -->
<div class="stat-card">
<h3>Run Monthly Billing</h3>

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


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

<br><br>

<button type="button" onclick="showStep2()" class="btn btn-primary">
⚡ Next
</button>
</div>

<!-- STEP 2 (HIDDEN INITIALLY) -->
<div class="stat-card" id="step2" style="display:<?= $showStep2 ? 'block' : 'none' ?>;margin-top:20px;">

<h3>Select Billing Mode</h3>

<label><input type="radio" name="billing_mode" value="full" checked> Full Billing</label><br>
<label><input type="radio" name="billing_mode" value="rental"> Rental Only</label><br>
<label><input type="radio" name="billing_mode" value="utilities"> Utilities Only</label><br>
<label><input type="radio" name="billing_mode" value="custom"> Custom</label><br><br>

<label><input type="checkbox" name="include_meter"> Include Meter</label><br>
<label><input type="checkbox" name="include_unit"> Include Unit</label><br>
<label><input type="checkbox" name="include_account"> Include Account</label><br>

<br>

<button type="submit" name="run_billing" class="btn btn-primary">
🚀 Run Billing
</button>

</div>

</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>

<script>
function showStep2(){
    document.getElementById('step2').style.display = 'block';
}
</script>

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