<?php
require_once __DIR__ . '/../config/auth.php';
header('Content-Type: application/json');

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

$pdo = getDB();

$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
    $input = $_POST;
}

$customer_id = !empty($input['customer_id']) ? (int)$input['customer_id'] : null;
$discount_type = $input['discount_type'] ?? 'Percentage';
$discount_value = (float)($input['discount_value'] ?? 0);
$tax_type = $input['tax_type'] ?? 'Percentage';
$tax_value = (float)($input['tax_value'] ?? 0);
$payment_method = $input['payment_method'] ?? 'Cash';
$paid_amount = (float)($input['paid_amount'] ?? 0);
$items = $input['items'] ?? [];

if (empty($items)) {
    echo json_encode(['success' => false, 'message' => 'No items in cart.']);
    exit;
}

try {
    $pdo->beginTransaction();

    $invoice_no = generateInvoiceNo();
    $subtotal = 0;
    $item_details = [];

    foreach ($items as $item) {
        $price = (float)($item['selling_price'] ?? $item['price'] ?? 0);
        $qty = (int)($item['quantity'] ?? $item['qty'] ?? 0);
        $product_id = (int)($item['product_id'] ?? $item['productId'] ?? 0);
        $product_name = $item['product_name'] ?? '';
        $total = $price * $qty;
        $subtotal += $total;

        if (empty($product_name)) {
            $stmt = $pdo->prepare("SELECT product_name, warranty_period_days FROM products WHERE id = ?");
            $stmt->execute([$product_id]);
            $prod = $stmt->fetch();
            $product_name = $prod ? $prod['product_name'] : '';
            $warranty_days = $prod ? (int)$prod['warranty_period_days'] : 0;
        } else {
            $stmt = $pdo->prepare("SELECT warranty_period_days FROM products WHERE id = ?");
            $stmt->execute([$product_id]);
            $prod = $stmt->fetch();
            $warranty_days = $prod ? (int)$prod['warranty_period_days'] : 0;
        }

        $item_details[] = [
            'product_id' => $product_id,
            'product_name' => $product_name,
            'imei_id' => isset($item['imei_id']) && $item['imei_id'] ? (int)$item['imei_id'] : null,
            'price' => $price,
            'qty' => $qty,
            'total' => $total,
            'warranty_days' => $warranty_days
        ];
    }

    $discount_amount = $discount_type === 'Percentage' ? ($subtotal * $discount_value / 100) : $discount_value;
    if ($discount_amount > $subtotal) $discount_amount = $subtotal;
    $after_discount = $subtotal - $discount_amount;

    $tax_amount = $tax_type === 'Percentage' ? ($after_discount * $tax_value / 100) : $tax_value;
    $total_amount = $after_discount + $tax_amount;

    $due_amount = $total_amount - $paid_amount;
    $status = $due_amount <= 0 ? 'Paid' : ($paid_amount > 0 ? 'Partial' : 'Due');

    $stmt = $pdo->prepare("INSERT INTO sales_invoices (invoice_no, customer_id, invoice_date, subtotal, discount_type, discount_value, discount_amount, tax_amount, total_amount, paid_amount, due_amount, payment_method, payment_status, invoice_status, created_by) VALUES (?,?,NOW(),?,?,?,?,?,?,?,?,?,?,?,?)");
    $stmt->execute([$invoice_no, $customer_id, $subtotal, $discount_type, $discount_value, $discount_amount, $tax_amount, $total_amount, $paid_amount, $due_amount, $payment_method, $status, 'Active', $_SESSION['user_id']]);
    $sale_id = $pdo->lastInsertId();

    $item_stmt = $pdo->prepare("INSERT INTO sales_invoice_items (sales_invoice_id, product_id, imei_id, product_name, quantity, selling_price, total_price, warranty_period_days) VALUES (?,?,?,?,?,?,?,?)");
    $stock_stmt = $pdo->prepare("UPDATE products SET current_stock = current_stock - ? WHERE id = ?");
    $stock_move = $pdo->prepare("INSERT INTO stock_movements (product_id, movement_type, quantity_out, reference_type, reference_id, created_by) VALUES (?, 'sale', ?, 'sale', ?, ?)");

    foreach ($item_details as $det) {
        $item_stmt->execute([$sale_id, $det['product_id'], $det['imei_id'], $det['product_name'], $det['qty'], $det['price'], $det['total'], $det['warranty_days']]);
        $stock_stmt->execute([$det['qty'], $det['product_id']]);
        $stock_move->execute([$det['product_id'], $det['qty'], $sale_id, $_SESSION['user_id']]);

        if ($det['imei_id']) {
            $stmt = $pdo->prepare("UPDATE product_imei SET status = 'Sold', sales_invoice_item_id = ? WHERE id = ?");
            $stmt->execute([$det['product_id'], $det['imei_id']]);
        }
    }

    if ($paid_amount > 0) {
        $payment_no = generatePaymentNo();
        $stmt = $pdo->prepare("INSERT INTO payments (payment_no, payment_type, reference_id, customer_id, amount, payment_method, payment_date, received_by) VALUES (?,'Sale',?,?,?,?,NOW(),?)");
        $stmt->execute([$payment_no, $sale_id, $customer_id, $paid_amount, $payment_method, $_SESSION['user_id']]);
    }

    if ($customer_id) {
        $stmt = $pdo->prepare("UPDATE customers SET current_balance = current_balance + ? WHERE id = ?");
        $stmt->execute([$due_amount, $customer_id]);
    }

    foreach ($item_details as $det) {
        if ($det['warranty_days'] > 0) {
            $stmt = $pdo->prepare("INSERT INTO warranty_records (reference_type, reference_id, product_id, imei_id, customer_id, warranty_start_date, warranty_end_date, warranty_type, warranty_status) VALUES ('sales_invoice',?,?,?,?,CURDATE(),DATE_ADD(CURDATE(), INTERVAL ? DAY),'product','Active')");
            $stmt->execute([$sale_id, $det['product_id'], $det['imei_id'], $customer_id, $det['warranty_days']]);
        }
    }

    $pdo->commit();

    logActivity('Created Sale', 'POS', $sale_id, "Invoice: $invoice_no, Amount: $total_amount");

    echo json_encode([
        'success' => true,
        'invoice_no' => $invoice_no,
        'invoice_id' => $sale_id,
        'total' => $total_amount
    ]);

} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}


