<?php
session_start();
require '../assets/db_connect.php';

// Check if form submitted via POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status'=>'error','message'=>'Invalid request method']);
    exit;
}

// Get data
$invoice_no = $_POST['invoice_no'] ?? '';
$customer_name = trim($_POST['customer_name'] ?? '');
$paid = floatval($_POST['paid'] ?? 0);
$items = $_POST['items'] ?? [];

if (empty($items)) {
    echo json_encode(['status'=>'error','message'=>'No items added']);
    exit;
}

try {
    $pdo->beginTransaction();

    // If customer name provided, insert into customers table
    $customer_id = null;
    if ($customer_name) {
        $stmt = $pdo->prepare("INSERT INTO customers (name) VALUES (?)");
        $stmt->execute([$customer_name]);
        $customer_id = $pdo->lastInsertId();
    }

    // Calculate total
    $total = 0;
    foreach ($items as $item) {
        $line_total = ($item['qty'] * $item['unit_price']) - $item['discount'];
        if ($line_total < 0) $line_total = 0;
        $total += $line_total;
    }

    // Insert sale
    $stmt = $pdo->prepare("INSERT INTO sales (invoice_no, customer_id, total, paid, status, created_by) VALUES (?, ?, ?, ?, ?, ?)");
    $status = ($paid >= $total) ? 'paid' : (($paid>0) ? 'partially_paid' : 'open');
    $stmt->execute([$invoice_no, $customer_id, $total, $paid, $status, $_SESSION['user_id'] ?? null]);
    $sale_id = $pdo->lastInsertId();

    // Insert sale lines and update batch stock
    $stmt_line = $pdo->prepare("INSERT INTO sale_lines (sale_id, product_id, batch_id, qty, unit_price, discount, line_total) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt_update = $pdo->prepare("UPDATE product_batches SET qty = qty - ? WHERE id=? AND qty>=?");

    foreach ($items as $item) {
        $line_total = ($item['qty'] * $item['unit_price']) - $item['discount'];
        if ($line_total < 0) $line_total = 0;

        // Insert line
        $stmt_line->execute([$sale_id, $item['product_id'], $item['batch_id'], $item['qty'], $item['unit_price'], $item['discount'], $line_total]);

        // Update batch stock
        $stmt_update->execute([$item['qty'], $item['batch_id'], $item['qty']]);

        if ($stmt_update->rowCount() == 0) {
            throw new Exception("Not enough stock for batch ID {$item['batch_id']}");
        }
    }

    $pdo->commit();
    echo json_encode(['status'=>'success','message'=>'Sale saved successfully!']);
} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
}
