<?php
require_once '../../../auth/check_session.php';
require_once '../../../config/database.php';

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

try {
    $db = getDatabaseConnection();
    $db->beginTransaction();
    
    $shop_id = $_SESSION['user']['shop_id'];
    $user_id = $_SESSION['user']['id'];
    
    // Generate invoice number
    $invoice_no = 'POS-' . date('Ymd-His') . '-' . str_pad(rand(0, 999), 3, '0', STR_PAD_LEFT);
    
    // Calculate totals
    $subtotal = $input['subtotal'] ?? 0;
    $discount_amount = $input['discount_amount'] ?? 0;
    $vat_amount = $input['vat_amount'] ?? 0;
    $total = $input['total'] ?? 0;
    
    // Create sale record
    $sql = "INSERT INTO sales 
            (invoice_no, sale_date, customer_id, total, paid, status, created_by, shop_id)
            VALUES (?, NOW(), ?, ?, ?, 'paid', ?, ?)";
    
    $stmt = $db->prepare($sql);
    $stmt->execute([
        $invoice_no,
        $input['customer_id'] ?? null,
        $total,
        $total, // Assume full payment for POS
        $user_id,
        $shop_id
    ]);
    
    $sale_id = $db->lastInsertId();
    
    // Add sale lines and inventory movements
    foreach ($input['items'] as $item) {
        // Add sale line
        $sql = "INSERT INTO sale_lines 
                (sale_id, product_id, batch_id, qty, unit_price, line_total, shop_id)
                VALUES (?, ?, ?, ?, ?, ?, ?)";
        
        $line_total = $item['price'] * $item['qty'];
        
        $stmt = $db->prepare($sql);
        $stmt->execute([
            $sale_id,
            $item['product_id'],
            $item['batch_id'],
            $item['qty'],
            $item['price'],
            $line_total,
            $shop_id
        ]);
        
        // Add inventory movement (deduct stock)
        $sql = "INSERT INTO inventory_movements 
                (product_id, batch_id, change_qty, movement_type, reference_id, created_by, shop_id)
                VALUES (?, ?, ?, 'SALE', ?, ?, ?)";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([
            $item['product_id'],
            $item['batch_id'],
            $item['qty'],
            $sale_id,
            $user_id,
            $shop_id
        ]);
    }
    
    // Add payment record
    $sql = "INSERT INTO payments 
            (sale_id, amount, method, paid_at, created_by, shop_id)
            VALUES (?, ?, ?, NOW(), ?, ?)";
    
    $stmt = $db->prepare($sql);
    $stmt->execute([
        $sale_id,
        $total,
        $input['payment_method'],
        $user_id,
        $shop_id
    ]);
    
    $db->commit();
    
    echo json_encode([
        'success' => true,
        'sale_id' => $sale_id,
        'invoice_no' => $invoice_no,
        'message' => 'Sale completed successfully'
    ]);
    
} catch (PDOException $e) {
    $db->rollBack();
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>