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

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

/* ===============================
FORM DATA
================================ */

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

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


/* ===============================
GENERATE QUOTE NUMBER (TENANT SAFE)
================================ */

$stmt = $pdo->prepare("
SELECT id
FROM quotations
WHERE company_id = ?
ORDER BY id DESC
LIMIT 1
");

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

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

$next = $last ? $last['id'] + 1 : 1;

$quote_number = "Q-" . date("Y") . "-" . str_pad($next,4,"0",STR_PAD_LEFT);


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

$subtotal = 0;

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

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

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

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

}

/* VAT */

$vat = 0;

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

$total = $subtotal + $vat;


/* ===============================
INSERT QUOTATION
================================ */

$stmt = $pdo->prepare("
INSERT INTO quotations
(
company_id,
customer_id,
quote_number,
quote_date,
valid_until,
subtotal,
vat_total,
total,
created_by,
vat_enabled
)
VALUES
(?,?,?,?,?,?,?,?,?,?)
");

$stmt->execute([
$company_id,
$customer_id,
$quote_number,
date("Y-m-d"),
$valid_until,
$subtotal,
$vat,
$total,
$user_id,
$apply_vat
]);

$quotation_id = $pdo->lastInsertId();


/* ===============================
INSERT 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 SNAPSHOT
================================ */

$stmt = $pdo->prepare("
SELECT sku, product_name
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([
$quotation_id,
$company_id,
$product_id,
$sku,
$name,
$description,
$qty,
$price,
$line_total,
$comment
]);

}


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

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