<?php

ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);

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

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

$company_id = $_SESSION['company_id'] ?? 0;

if(!$company_id){
die("Company not identified.");
}

$customer_id = $_POST['customer_id'] ?? null;
$apply_vat   = $_POST['apply_vat'] ?? 0;

if(empty($customer_id)){
die("Customer is required.");
}

if(empty($_POST['label']) || empty($_POST['units']) || empty($_POST['rate'])){
die("Invoice items are required.");
}

/* ===============================
CALCULATE TOTALS
================================ */

$subtotal = 0;

foreach($_POST['label'] as $i => $label){

$label = trim($label ?? '');
$units = (float)($_POST['units'][$i] ?? 0);
$rate  = (float)($_POST['rate'][$i] ?? 0);

if($label === ''){
continue;
}

$subtotal += ($units * $rate);

}

$vat_total = 0;

if($apply_vat == 1){
$vat_total = $subtotal * 0.15;
}

$total = $subtotal + $vat_total;

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

$stmt = $pdo->prepare("
INSERT INTO invoices
(
company_id,
customer_id,
subtotal,
vat_total,
total,
vat_enabled,
created_at
)
VALUES
(?,?,?,?,?,?,NOW())
");

$stmt->execute([
$company_id,
$customer_id,
$subtotal,
$vat_total,
$total,
$apply_vat
]);

$invoice_id = $pdo->lastInsertId();

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

$line_order = 1;

foreach($_POST['label'] as $i => $label){

$label = trim($label ?? '');
$units = (float)($_POST['units'][$i] ?? 0);
$rate  = (float)($_POST['rate'][$i] ?? 0);

if($label === ''){
continue;
}

$amount = $units * $rate;

$stmt = $pdo->prepare("
INSERT INTO invoice_items
(
invoice_id,
label,
units,
rate,
amount,
line_order
)
VALUES
(?,?,?,?,?,?)
");

$stmt->execute([
$invoice_id,
$label,
$units,
$rate,
$amount,
$line_order
]);

$line_order++;

}

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

header("Location: view.php?id=".$invoice_id);
exit;