<?php
ob_start();
session_start();
chdir('../');
require_once("public/connection.php");
require_once("public/functions.php");


if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // Get posted invoice info
    $invoice_no = $_POST['invoice_no'] ?? '';
    $reg_number = $_POST['reg_number'] ?? '';
    $cashier = $_POST['cashier'] ?? '';
    $student_name = $_POST['student_name'] ?? '';
    $student_class = $_POST['student_class'] ?? '';
    $total_amount = floatval($_POST['total_amount'] ?? 0);
    $amount_paid = floatval($_POST['amount_paid'] ?? 0);

    $balance = $total_amount - $amount_paid;
    
    // Payment status logic
    if ($amount_paid <= 0) {
        $payment_status = 'Unpaid';
    } elseif ($balance <= 0) {
        $payment_status = 'Paid';
    } else {
        $payment_status = 'Balance';
    }

    // Invoice items arrays
    $item_names = $_POST['item_name'] ?? [];
    $quantities = $_POST['quantity'] ?? [];
    $unit_prices = $_POST['unit_price'] ?? [];

    // Validate required fields
    if (!$invoice_no || !$reg_number || !$student_name || !$student_class || $total_amount <= 0) {
        $_SESSION['msg'] = "Please fill all required fields.";
        $_SESSION['type'] = "danger";
        header('Location: invoice_create');
        exit;
    }

    // Start transaction
    $connection->begin_transaction();

    try {
        // Insert invoice with created_by
        $stmt = $connection->prepare("INSERT INTO inventory_invoices 
            (invoice_no, reg_number, student_name, student_class, total_amount, amount_paid, balance, payment_status, created_by, issued_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
        $stmt->bind_param('ssssdddss', $invoice_no, $reg_number, $student_name, $student_class, $total_amount, $amount_paid, $balance, $payment_status, $cashier);
        $stmt->execute();

        $invoice_id = $stmt->insert_id;
        $stmt->close();

        // Insert invoice items
        $stmt = $connection->prepare("INSERT INTO inventory_invoice_items (invoice_id, item_name, quantity, unit_price, total_price) VALUES (?, ?, ?, ?, ?)");

        foreach ($item_names as $index => $name) {
            $name = trim($name);
            $qty = floatval($quantities[$index] ?? 0);
            $price = floatval($unit_prices[$index] ?? 0);
            $total = $qty * $price;

            if (!$name || $qty <= 0 || $price <= 0) continue;

            $stmt->bind_param('isidd', $invoice_id, $name, $qty, $price, $total);
            $stmt->execute();
        }

        $stmt->close();
        $connection->commit();

        $_SESSION['msg'] = "Invoice saved successfully!";
        $_SESSION['type'] = "success";
        header('Location: view_invoice');
        exit;

    } catch (Exception $e) {
        $connection->rollback();

        $_SESSION['msg'] = "Error saving invoice: " . $e->getMessage();
        $_SESSION['type'] = "danger";
        header('Location: invoice_create');
        exit;
    }
} else {
    header('Location: invoice_create');
    exit;
}
?>
