prepare("DELETE FROM invoices WHERE id = ?"); $stmt->execute([$delete_id]); header("Location: invoices.php"); exit; } // Handle Add Invoice if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_invoice'])) { $customer_id = $_POST['customer_id']; $invoice_date = $_POST['invoice_date']; $due_date = $_POST['due_date']; $total = $_POST['total']; $status = $_POST['status']; try { $sql = "INSERT INTO invoices (customer_id, invoice_date, due_date, total, status) VALUES (:customer_id, :invoice_date, :due_date, :total, :status)"; $stmt = db()->prepare($sql); $stmt->execute([ ':customer_id' => $customer_id, ':invoice_date' => $invoice_date, ':due_date' => $due_date, ':total' => $total, ':status' => $status ]); header("Location: invoices.php"); exit(); } catch (PDOException $e) { $error_message = "Error adding invoice: " . $e->getMessage(); } } // Handle form submission for updating an invoice if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_invoice'])) { $id = $_POST['invoice_id']; $customer_id = $_POST['customer_id']; $invoice_date = $_POST['invoice_date']; $due_date = $_POST['due_date']; $total = $_POST['total']; $status = $_POST['status']; if (!empty($id)) { $pdo = db(); $stmt = $pdo->prepare("UPDATE invoices SET customer_id = ?, invoice_date = ?, due_date = ?, total = ?, status = ? WHERE id = ?"); $stmt->execute([$customer_id, $invoice_date, $due_date, $total, $status, $id]); header("Location: invoices.php"); exit; } } // Fetch invoices and customers try { $invoices_stmt = db()->query("SELECT i.*, c.companyName as customer_name FROM invoices i JOIN customers c ON i.customer_id = c.id ORDER BY i.invoice_date DESC"); $invoices = $invoices_stmt->fetchAll(PDO::FETCH_ASSOC); $customers_stmt = db()->query("SELECT id, companyName FROM customers ORDER BY companyName ASC"); $customers = $customers_stmt->fetchAll(PDO::FETCH_ASSOC); } catch (PDOException $e) { $error_message = "Error fetching data: " . $e->getMessage(); $invoices = []; $customers = []; } include 'includes/header.php'; ?>