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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die("Invalid request.");
}

$meterId = (int)$_POST['meter_id'];
$start   = $_POST['start'];
$end     = $_POST['end'];

/* ===============================
   GET COMPANY + TARIFF
================================= */

$stmt = $pdo->prepare("
    SELECT 
        c.id AS company_id,
        c.company_name,
        m.tariff_id
    FROM operational_meters m
    JOIN companies c ON c.id = m.company_id
    WHERE m.id = ?
    LIMIT 1
");

$stmt->execute([$meterId]);
$data = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$data) {
    die("Operational meter not found.");
}

$companyId = (int)$data['company_id'];
$tariffId  = (int)$data['tariff_id'];

if (!$tariffId) {
    die("No tariff assigned to this meter.");
}


/* ===============================
   GET CONSUMPTION
================================= */

$stmt = $pdo->prepare("
    SELECT SUM(daily_consumption)
    FROM meter_readings
    WHERE meter_id = ?
    AND reading_date BETWEEN ? AND ?
");

$stmt->execute([$meterId, $start, $end]);

$totalConsumption = (float)($stmt->fetchColumn() ?? 0);


/* ===============================
   CALCULATE BILL
================================= */

$bill = calculateBlockBill($pdo, $tariffId, $totalConsumption);

$subtotal  = $bill['total'];
$breakdown = $bill['breakdown'];


/* ===============================
   VAT
================================= */

$vatRate = 15.00;
$vatAmount = ($subtotal * $vatRate) / 100;
$totalAmount = $subtotal + $vatAmount;


/* ===============================
   PREVENT DUPLICATE INVOICE
================================= */

$stmt = $pdo->prepare("
SELECT id
FROM invoices
WHERE meter_id = ?
AND period_start = ?
AND period_end = ?
LIMIT 1
");

$stmt->execute([$meterId, $start, $end]);

$existingInvoice = $stmt->fetch(PDO::FETCH_ASSOC);

if ($existingInvoice) {

    header("Location: invoice_view.php?id=".$existingInvoice['id']);
    exit;

}


/* ===============================
   GENERATE INVOICE NUMBER
================================= */

$pdo->beginTransaction();

try {

$ym = date('Y-m');

$stmt = $pdo->prepare("
    SELECT last_seq
    FROM invoice_counters
    WHERE company_id = ? AND ym = ?
    FOR UPDATE
");

$stmt->execute([$companyId, $ym]);

$counter = $stmt->fetch(PDO::FETCH_ASSOC);


if (!$counter) {

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

    $sequence = 1;

} else {

    $sequence = $counter['last_seq'] + 1;

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

}


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


/* ===============================
   INSERT INVOICE
================================= */

$status = 'ISSUED';
$dueDate = date('Y-m-d', strtotime('+30 days'));

$stmt = $pdo->prepare("
    INSERT INTO invoices
    (company_id, meter_id, tariff_id, invoice_number, invoice_date,
     due_date, period_start, period_end, consumption,
     subtotal, vat_rate, vat_amount, total, status, created_by)
    VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
");

$stmt->execute([
    $companyId,
    $meterId,
    $tariffId,
    $invoiceNumber,
    date('Y-m-d'),
    $dueDate,
    $start,
    $end,
    $totalConsumption,
    $subtotal,
    $vatRate,
    $vatAmount,
    $totalAmount,
    $status,
    $_SESSION['user_id']
]);

$invoiceId = $pdo->lastInsertId();


/* ===============================
   INSERT LINE ITEMS
================================= */

foreach ($breakdown as $index => $row) {

    $pdo->prepare("
        INSERT INTO invoice_items
        (invoice_id, line_order, label, units, rate, amount)
        VALUES (?,?,?,?,?,?)
    ")->execute([
        $invoiceId,
        $index + 1,
        $row['label'],
        $row['units'],
        $row['rate'],
        $row['amount']
    ]);

}


$pdo->commit();


/* ===============================
   REDIRECT
================================= */

header("Location: invoice_view.php?id=".$invoiceId);
exit;

} catch(Exception $e){

$pdo->rollBack();
die("Invoice generation failed: ".$e->getMessage());

}