<?php
session_start();
require_once 'config/database.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';
requireLogin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: documents.php');
    exit;
}

$userId = $_SESSION['user_id'];

$stmt = $pdo->prepare("SELECT id, currency FROM companies WHERE user_id = ? LIMIT 1");
$stmt->execute([$userId]);
$company = $stmt->fetch();

if (!$company) {
    header('Location: settings.php');
    exit;
}

$companyId = $company['id'];
$id = $_POST['id'] ?? 0;
$type = $_POST['type'] ?? 'invoice';
$document_number = trim($_POST['document_number'] ?? '');
$client_id = $_POST['client_id'] ?? 0;
$issue_date = $_POST['issue_date'] ?? date('Y-m-d');
$due_date = $_POST['due_date'] ?? null;
$subtotal = floatval($_POST['subtotal'] ?? 0);
$tax_amount = floatval($_POST['tax_amount'] ?? 0);
$discount_type = $_POST['discount_type'] ?? 'percentage';
$discount_value = floatval($_POST['discount_value'] ?? 0);
$discount_amount = floatval($_POST['discount_amount'] ?? 0);
$total = floatval($_POST['total'] ?? 0);
$notes = trim($_POST['notes'] ?? '');
$terms = trim($_POST['terms'] ?? '');
$status = ($_POST['action'] ?? 'save_draft') == 'save_send' ? 'sent' : 'draft';

if (empty($document_number) || !$client_id) {
    $_SESSION['error'] = 'Document number and client are required.';
    header('Location: document-form.php?type=' . $type);
    exit;
}

try {
    if ($id) {
        $stmt = $pdo->prepare("UPDATE documents SET document_number=?, client_id=?, issue_date=?, due_date=?, subtotal=?, tax_amount=?, discount_type=?, discount_value=?, discount_amount=?, total=?, notes=?, terms=?, status=? WHERE id=? AND company_id=?");
        $stmt->execute([$document_number, $client_id, $issue_date, $due_date, $subtotal, $tax_amount, $discount_type, $discount_value, $discount_amount, $total, $notes, $terms, $status, $id, $companyId]);
        $stmt = $pdo->prepare("DELETE FROM document_items WHERE document_id = ?");
        $stmt->execute([$id]);
        $docId = $id;
    } else {
        $stmt = $pdo->prepare("INSERT INTO documents (company_id, type, document_number, client_id, issue_date, due_date, subtotal, tax_amount, discount_type, discount_value, discount_amount, total, notes, terms, status, currency) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$companyId, $type, $document_number, $client_id, $issue_date, $due_date, $subtotal, $tax_amount, $discount_type, $discount_value, $discount_amount, $total, $notes, $terms, $status, $company['currency']]);
        $docId = $pdo->lastInsertId();
    }

    $descriptions = $_POST['item_description'] ?? [];
    $quantities = $_POST['item_qty'] ?? [];
    $prices = $_POST['item_price'] ?? [];
    $taxes = $_POST['item_tax'] ?? [];

    for ($i = 0; $i < count($descriptions); $i++) {
        if (!empty($descriptions[$i])) {
            $qty = floatval($quantities[$i] ?? 1);
            $price = floatval($prices[$i] ?? 0);
            $tax = floatval($taxes[$i] ?? 0);
            $itemTotal = $qty * $price;
            $stmt = $pdo->prepare("INSERT INTO document_items (document_id, description, quantity, unit_price, tax_rate, total) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$docId, $descriptions[$i], $qty, $price, $tax, $itemTotal]);
        }
    }

    header('Location: documents.php?msg=saved');
} catch (PDOException $e) {
    error_log("Document save error: " . $e->getMessage());
    $_SESSION['error'] = 'An error occurred while saving.';
    header('Location: document-form.php?type=' . $type . ($id ? '&id=' . $id : ''));
}
?>