<?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__ . '/../engine/calculate_block_bill.php';

/* ===============================
   GENERATE INVOICE NUMBER
================================ */
function generateInvoiceNumber(PDO $pdo, int $companyId): string
{
    $ym = date('Y-m');

    $stmt = $pdo->prepare("
        SELECT last_seq
        FROM invoice_counters
        WHERE company_id = ? AND ym = ?
        FOR UPDATE
    ");
    $stmt->execute([$companyId, $ym]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        $sequence = 1;

        $pdo->prepare("
            INSERT INTO invoice_counters (company_id, ym, last_seq)
            VALUES (?, ?, ?)
        ")->execute([$companyId, $ym, $sequence]);

    } else {
        $sequence = (int)$row['last_seq'] + 1;

        $pdo->prepare("
            UPDATE invoice_counters
            SET last_seq = ?
            WHERE company_id = ? AND ym = ?
        ")->execute([$sequence, $companyId, $ym]);
    }

    return 'INV-' . date('Ym') . '-' . str_pad($sequence, 4, '0', STR_PAD_LEFT);
}

/* ===============================
   CONSUMPTION
================================ */
function getConsumptionForPeriod(PDO $pdo, int $meterId, string $start, string $end): ?float
{
    $stmt = $pdo->prepare("
        SELECT reading_value
        FROM meter_readings
        WHERE meter_id = ?
        AND reading_date < ?
        ORDER BY reading_date DESC, id DESC
        LIMIT 1
    ");
    $stmt->execute([$meterId, $start]);
    $startReading = $stmt->fetchColumn();

    $stmt = $pdo->prepare("
        SELECT reading_value
        FROM meter_readings
        WHERE meter_id = ?
        AND reading_date <= ?
        ORDER BY reading_date DESC, id DESC
        LIMIT 1
    ");
    $stmt->execute([$meterId, $end]);
    $endReading = $stmt->fetchColumn();

    if ($startReading === false || $endReading === false) {
        return null;
    }

    $usage = (float)$endReading - (float)$startReading;
    if ($usage < 0) return null;

    return $usage;
}

/* ===============================
   HELPERS
================================ */
function insertLine(PDO $pdo, int $invoiceId, string $desc, float $qty, float $rate, float $total): void
{
    $pdo->prepare("
        INSERT INTO invoice_lines (invoice_id, description, quantity, unit_price, total)
        VALUES (?,?,?,?,?)
    ")->execute([$invoiceId, $desc, $qty, $rate, $total]);
}

function getSubtotal(PDO $pdo, int $invoiceId): float
{
    $stmt = $pdo->prepare("SELECT COALESCE(SUM(total),0) FROM invoice_lines WHERE invoice_id = ?");
    $stmt->execute([$invoiceId]);
    return (float)$stmt->fetchColumn();
}

function resolveBillingSelection(array $post): array
{
    $mode = $post['billing_mode'] ?? 'full';

    return match ($mode) {
        'full' => ['mode'=>$mode,'include_meter'=>true,'include_unit'=>true,'include_account'=>true],
        'rental' => ['mode'=>$mode,'include_meter'=>false,'include_unit'=>true,'include_account'=>true],
        'utilities' => ['mode'=>$mode,'include_meter'=>true,'include_unit'=>false,'include_account'=>false],
        'custom' => [
            'mode'=>$mode,
            'include_meter'=>isset($post['include_meter']),
            'include_unit'=>isset($post['include_unit']),
            'include_account'=>isset($post['include_account'])
        ],
    };
}

/* ===============================
   LOAD PERIOD
================================ */
$period = $pdo->query("SELECT * FROM billing_periods WHERE status = 'OPEN' LIMIT 1")->fetch(PDO::FETCH_ASSOC);
if (!$period) die("No billing period");

$start = $period['period_start'];
$end   = $period['period_end'];
$vatRate = 0.15;

/* ===============================
   EXECUTION
================================ */
if (!isset($_POST['run_billing'])) {
    header('Location: index_preview.php');
    exit;
}

$selection = resolveBillingSelection($_POST);

$includeMeter   = $selection['include_meter'];
$includeUnit    = $selection['include_unit'];
$includeAccount = $selection['include_account'];
$billingMode    = $selection['mode'];

$created = 0;
$skipped = 0;
$totalBilled = 0;

/* LOAD ACCOUNTS */
$accounts = $pdo->query("
SELECT ba.*, s.company_id
FROM billing_accounts ba
JOIN structures s ON s.id = ba.structure_id
")->fetchAll(PDO::FETCH_ASSOC);

/* MAIN LOOP */
foreach ($accounts as $acc) {

    $accountId = (int)$acc['id'];
    $companyId = (int)$acc['company_id'];

    $units = ['ACCOUNT'];

    foreach ($units as $unitName) {

        $pdo->beginTransaction();

        try {

            $invoiceNumber = generateInvoiceNumber($pdo, $companyId);

            $pdo->prepare("
                INSERT INTO invoices
                (company_id, billing_account_id, unit_name, invoice_number, invoice_date, due_date, period_start, period_end, status, vat_rate)
                VALUES (?,?,?,?,?,?,?,?,?,?)
            ")->execute([
                $companyId,
                $accountId,
                $unitName,
                $invoiceNumber,
                date('Y-m-d'),
                date('Y-m-d', strtotime('+14 days')),
                $start,
                $end,
                'ISSUED',
                $vatRate
            ]);

            $invoiceId = (int)$pdo->lastInsertId();

            insertLine($pdo, $invoiceId, "Demo Charge", 1, 100, 100);

            $subtotal = getSubtotal($pdo, $invoiceId);
            $vat      = $subtotal * $vatRate;
            $total    = $subtotal + $vat;

            $pdo->prepare("
                UPDATE invoices
                SET subtotal=?, vat_amount=?, total=?
                WHERE id=?
            ")->execute([$subtotal,$vat,$total,$invoiceId]);

            $pdo->commit();

            $created++;
            $totalBilled += $total;

        } catch (Exception $e) {
            $pdo->rollBack();
            $skipped++;
        }
    }
}

/* ===============================
   UI OUTPUT
================================ */
require_once __DIR__ . '/../../../includes/layout.php';
?>

<div class="container">

<div class="card success-banner">
    <h2>✅ Billing Completed</h2>
    <p>All selected accounts processed successfully.</p>
</div>

<div class="kpi-grid">
    <div class="kpi"><h2><?= $created ?></h2><p>Invoices</p></div>
    <div class="kpi"><h2><?= $skipped ?></h2><p>Skipped</p></div>
    <div class="kpi"><h2><?= strtoupper($billingMode) ?></h2><p>Mode</p></div>
</div>

<div class="card">
    <h3>Summary</h3>
    <p><strong>Period:</strong> <?= $start ?> → <?= $end ?></p>
    <p><strong>VAT:</strong> <?= $vatRate * 100 ?>%</p>
</div>

</div>

<style>
.card{background:#fff;padding:20px;border-radius:12px;margin-bottom:20px;box-shadow:0 4px 10px rgba(0,0,0,0.05);}
.success-banner{background:#ecfdf5;border:1px solid #10b981;}
.kpi-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:15px;}
.kpi{text-align:center;background:#fff;padding:20px;border-radius:10px;}
</style>

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