<?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;
$user_id    = $_SESSION['user_id'] ?? 0;

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if(!$id){
die("Invalid quotation.");
}

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

/* ===============================
VERIFY QUOTATION BELONGS TO TENANT
================================ */

$stmt = $pdo->prepare("
SELECT id
FROM quotations
WHERE id = ?
AND company_id = ?
");

$stmt->execute([$id,$company_id]);

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

if(!$quote){
die("Quotation not found.");
}


/* ===============================
PREPARE ARRAYS
================================ */

$product_ids = $_POST['product_id'] ?? [];
$qtys        = $_POST['qty'] ?? [];
$prices      = $_POST['price'] ?? [];
$descs       = $_POST['description'] ?? [];
$comments    = $_POST['item_comment'] ?? [];


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

$subtotal = 0;

foreach($qtys as $i => $qty){

$price = $prices[$i] ?? 0;

$qty   = (float)$qty;
$price = (float)$price;

$subtotal += ($qty * $price);

}

$vat = 0;

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

$total = $subtotal + $vat;


/* ===============================
UPDATE QUOTATION HEADER
================================ */

$stmt = $pdo->prepare("
UPDATE quotations
SET
valid_until = ?,
subtotal = ?,
vat_total = ?,
total = ?,
vat_enabled = ?
WHERE id = ?
");

$stmt->execute([
$valid_until,
$subtotal,
$vat,
$total,
$apply_vat,
$id
]);


/* ===============================
DELETE OLD ITEMS
================================ */

$stmt = $pdo->prepare("
DELETE FROM quotation_items
WHERE quotation_id = ?
");

$stmt->execute([$id]);


/* ===============================
INSERT UPDATED ITEMS
================================ */

foreach($product_ids as $i => $product_id){

if(empty($product_id)){
continue;
}

$qty         = $qtys[$i] ?? 0;
$price       = $prices[$i] ?? 0;
$description = $descs[$i] ?? '';
$comment     = $comments[$i] ?? '';

$qty   = (float)$qty;
$price = (float)$price;

$line_total = $qty * $price;


/* ===============================
FETCH PRODUCT INFO
================================ */

$stmt = $pdo->prepare("
SELECT sku, product_name, item_type
FROM inventory_products
WHERE id = ?
AND company_id = ?
");

$stmt->execute([$product_id,$company_id]);

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

if(!$product){
continue;
}

$sku  = $product['sku'];
$name = $product['product_name'];


/* ===============================
INSERT ITEM
================================ */

$stmt = $pdo->prepare("
INSERT INTO quotation_items
(
quotation_id,
company_id,
product_id,
sku,
product_name,
description,
quantity,
unit_price,
total,
item_comment
)
VALUES
(?,?,?,?,?,?,?,?,?,?)
");

$stmt->execute([
$id,
$company_id,
$product_id,
$sku,
$name,
$description,
$qty,
$price,
$line_total,
$comment
]);

}


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

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