beginTransaction(); // Fetch quotation $stmt = db()->prepare("SELECT * FROM quotations WHERE id = ? AND deleted_at IS NULL"); $stmt->execute([$quotation_id]); $quotation = $stmt->fetch(); if (!$quotation) { throw new Exception("Quotation not found"); } if ($quotation['status'] !== 'Approved') { throw new Exception("Only approved quotations can be converted to invoices"); } // Generate invoice number $invoice_number = 'INV-' . date('Ymd') . '-' . strtoupper(bin2hex(random_bytes(2))); $due_date = date('Y-m-d', strtotime('+14 days')); // Create invoice $stmt = db()->prepare("INSERT INTO invoices (invoice_number, quotation_id, customer_id, user_id, issue_date, due_date, status, subtotal, tax_amount, total_amount, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); $stmt->execute([ $invoice_number, $quotation_id, $quotation['customer_id'], $_SESSION['user_id'], // Current user (Finance/Admin) who converts it date('Y-m-d'), $due_date, 'Unpaid', $quotation['subtotal'], $quotation['tax_amount'], $quotation['total_amount'], $quotation['notes'] ]); $invoice_id = db()->lastInsertId(); // Copy items $stmt = db()->prepare("SELECT * FROM quotation_items WHERE quotation_id = ?"); $stmt->execute([$quotation_id]); $items = $stmt->fetchAll(); $item_stmt = db()->prepare("INSERT INTO invoice_items (invoice_id, product_id, quantity, unit_price, total_price) VALUES (?, ?, ?, ?, ?)"); foreach ($items as $item) { $item_stmt->execute([ $invoice_id, $item['product_id'], $item['quantity'], $item['unit_price'], $item['total_price'] ]); } // Log action $log_stmt = db()->prepare("INSERT INTO audit_logs (user_id, action, entity_type, entity_id, details) VALUES (?, ?, ?, ?, ?)"); $log_stmt->execute([$_SESSION['user_id'], 'CREATE', 'INVOICE', $invoice_id, "Number: $invoice_number (from QTN ID: $quotation_id)"]); db()->commit(); $_SESSION['success'] = "Quotation converted to invoice successfully."; header("Location: invoices.php"); exit; } catch (Exception $e) { db()->rollBack(); $_SESSION['error'] = "Error converting to invoice: " . $e->getMessage(); header("Location: quotations.php"); exit; }