<?php
session_start();
header('Content-Type: application/json');

// ১. সিকিউরিটি চেক: ইউজার লগইন করা না থাকলে ডাটা সেভ হবে না
if (!isset($_SESSION['user_logged_in']) || $_SESSION['user_logged_in'] !== true) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized. Please login to save invoices.']);
    exit;
}

// ২. ডাটাবেস কানেকশন যুক্ত করা
require_once '../../config.php'; 

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id = $_SESSION['user_id'];
    
    // সাধারণ তথ্যগুলো গ্রহণ
    $invoice_number = trim($_POST['invoice_number'] ?? '');
    $from_text = trim($_POST['from_text'] ?? '');
    $to_text = trim($_POST['to_text'] ?? '');
    $invoice_date = !empty($_POST['date']) ? $_POST['date'] : date('Y-m-d');
    $due_date = !empty($_POST['due_date']) ? $_POST['due_date'] : null;
    $currency_symbol = $_POST['currency_symbol'] ?? '$';
    $theme_color = $_POST['theme_color'] ?? '#2ecc71';
    
    // আইটেমগুলো প্রসেস করে JSON বানানো
    $items = [];
    $subtotal = 0;
    if (isset($_POST['item_desc']) && is_array($_POST['item_desc'])) {
        for ($i = 0; $i < count($_POST['item_desc']); $i++) {
            $desc = trim($_POST['item_desc'][$i]);
            $rate = floatval($_POST['item_rate'][$i]);
            $qty = floatval($_POST['item_qty'][$i]);
            $total = $rate * $qty;
            
            if ($desc !== '' || $total > 0) {
                $subtotal += $total;
                $items[] =['desc' => $desc, 'rate' => $rate, 'qty' => $qty, 'total' => $total];
            }
        }
    }
    $items_json = json_encode($items, JSON_UNESCAPED_UNICODE);

    // ক্যালকুলেশন
    $discount_amount = floatval($_POST['discount_amount'] ?? 0);
    $discount_type = $_POST['discount_type'] ?? 'percent';
    $calc_discount = ($discount_type === 'percent') ? ($subtotal * ($discount_amount / 100)) : $discount_amount;
    
    $after_discount = $subtotal - $calc_discount;
    
    $tax_amount = floatval($_POST['tax_amount'] ?? 0);
    $tax_type = $_POST['tax_type'] ?? 'percent';
    $calc_tax = ($tax_type === 'percent') ? ($after_discount * ($tax_amount / 100)) : $tax_amount;
    
    $shipping_amount = floatval($_POST['shipping_amount'] ?? 0);
    $amount_paid = floatval($_POST['amount_paid'] ?? 0);
    
    $total_due = $after_discount + $calc_tax + $shipping_amount;
    $balance_due = $total_due - $amount_paid;
    
    $notes = trim($_POST['notes'] ?? '');
    $terms = trim($_POST['terms'] ?? '');

    // ৩. ডাটাবেসে সেভ করা (SQL Injection প্রোটেকশন সহ)
    $stmt = $conn->prepare("INSERT INTO user_invoices 
        (user_id, invoice_number, from_text, to_text, invoice_date, due_date, currency_symbol, theme_color, subtotal, discount_amount, tax_amount, shipping_amount, total_due, amount_paid, balance_due, items_data, notes, terms) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
    $stmt->bind_param("isssssssdddddddsss", 
        $user_id, $invoice_number, $from_text, $to_text, $invoice_date, $due_date, 
        $currency_symbol, $theme_color, $subtotal, $calc_discount, $calc_tax, 
        $shipping_amount, $total_due, $amount_paid, $balance_due, $items_json, $notes, $terms
    );
    
    if ($stmt->execute()) {
        echo json_encode(['status' => 'success', 'message' => 'Invoice saved automatically!', 'id' => $stmt->insert_id]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $stmt->error]);
    }
    $stmt->close();
}
?>