<?php

/* ===============================
ERROR DISPLAY
================================ */

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

try {

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

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

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

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

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

/* ===============================
FETCH QUOTE
================================ */

if($role_id == 7){

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

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

}else{

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

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

}

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

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


/* ===============================
PREVENT DOUBLE CONVERSION
================================ */

if(strtoupper($quote['status'] ?? '') === 'CONVERTED'){
die("This quotation has already been converted.");
}


/* ===============================
START DATABASE TRANSACTION
================================ */

$pdo->beginTransaction();


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

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

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

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

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

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


/* ===============================
CREATE INVOICE
================================ */

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

$stmt->execute([
$quote['company_id'],
$quote['customer_id'],
$quote['id'],
$invoice_number,
$quote['subtotal'],
$quote['vat_total'],
$quote['total'],
$quote['vat_enabled']
]);

$invoice_id = $pdo->lastInsertId();


/* ===============================
COPY ITEMS
================================ */

$stmt = $pdo->prepare("
SELECT *
FROM quotation_items
WHERE quotation_id = ?
ORDER BY id ASC
");

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

$items = $stmt->fetchAll(PDO::FETCH_ASSOC);

$order = 1;

foreach($items as $item){

$label = trim(
($item['product_name'] ?? '') .
' ' .
($item['sku'] ?? '')
);

if(!empty($item['description'])){
$label .= ' - ' . $item['description'];
}

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

$stmt->execute([
$invoice_id,
$item['product_id'],   // this links invoice to inventory
$label,
$item['quantity'],
$item['unit_price'],
$item['total'],
$order
]);

/* Reduce inventory stock */
if(!empty($item['product_id'])){

    $stmt = $pdo->prepare("
        UPDATE inventory_products
        SET stock_qty = stock_qty - ?
        WHERE id = ?
        AND track_inventory = 1
    ");

    $stmt->execute([
        $item['quantity'],
        $item['product_id']
    ]);

}

$order++;

}


/* ===============================
UPDATE QUOTE STATUS
================================ */

$stmt = $pdo->prepare("
UPDATE quotations
SET status = 'CONVERTED'
WHERE id = ?
");

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


/* ===============================
COMMIT TRANSACTION
================================ */

$pdo->commit();


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

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

} catch (Throwable $e) {

if($pdo->inTransaction()){
$pdo->rollBack();
}

echo "<h2>Conversion Error</h2>";
echo "<pre>";
echo $e->getMessage();
echo "</pre>";

}