<?php
// modules/sales/ajax/process_sale.php
session_start();
require_once '../../assets/db_connect.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user'])) {
    echo json_encode(['status' => 'error', 'message' => 'Session expired']);
    exit;
}

$shop_id = $_SESSION['user']['shop_id'] ?? 0;
$user_id = $_SESSION['user']['id'] ?? 0;

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

if (!$data) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid data']);
    exit;
}

try {
    // Generate invoice number
    $invoice_no = 'SALE-' . date('YmdHis') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
    
    // Calculate total
    $total = 0;
    foreach ($data['items'] as $item) {
        $total += $item['qty'] * $item['unit_price'];
    }
    $total -= ($data['discount'] ?? 0);
    
    // Start transaction
    $pdo->beginTransaction();
    
    // Create sale record
    $sale_sql = "INSERT INTO sales (invoice_no, sale_date, customer_id, total, paid, status, created_by, shop_id) 
                 VALUES (?, NOW(), ?, ?, ?, ?, ?, ?)";
    $sale_stmt = $pdo->prepare($sale_sql);
    $paid = $data['payment']['amount'] ?? 0;
    $status = ($paid >= $total) ? 'paid' : ($paid > 0 ? 'partially_paid' : 'open');
    
    $sale_stmt->execute([
        $invoice_no,
        $data['customer_id'] ?? null,
        $total,
        $paid,
        $status,
        $user_id,
        $shop_id
    ]);
    
    $sale_id = $pdo->lastInsertId();
    
    // Create sale lines and update inventory
    foreach ($data['items'] as $item) {
        $line_total = $item['qty'] * $item['unit_price'];
        
        // Insert sale line
        $line_sql = "INSERT INTO sale_lines (sale_id, product_id, batch_id, qty, unit_price, line_total, shop_id) 
                     VALUES (?, ?, ?, ?, ?, ?, ?)";
        $line_stmt = $pdo->prepare($line_sql);
        $line_stmt->execute([
            $sale_id,
            $item['product_id'],
            $item['batch_id'],
            $item['qty'],
            $item['unit_price'],
            $line_total,
            $shop_id
        ]);
        
        // Create inventory movement
        $movement_sql = "INSERT INTO inventory_movements 
                        (product_id, batch_id, change_qty, movement_type, reference_id, created_by, shop_id) 
                        VALUES (?, ?, ?, 'SALE', ?, ?, ?)";
        $movement_stmt = $pdo->prepare($movement_sql);
        $movement_stmt->execute([
            $item['product_id'],
            $item['batch_id'],
            $item['qty'],
            $sale_id,
            $user_id,
            $shop_id
        ]);
    }
    
    // Create payment if any
    if ($paid > 0) {
        $payment_sql = "INSERT INTO payments (sale_id, amount, method, created_by, shop_id) 
                       VALUES (?, ?, ?, ?, ?)";
        $payment_stmt = $pdo->prepare($payment_sql);
        $payment_stmt->execute([
            $sale_id,
            $paid,
            $data['payment']['method'] ?? 'CASH',
            $user_id,
            $shop_id
        ]);
    }
    
    // Commit transaction
    $pdo->commit();
    
    echo json_encode([
        'status' => 'success',
        'message' => 'Sale processed successfully',
        'sale_id' => $sale_id,
        'invoice_no' => $invoice_no,
        'total' => $total
    ]);
    
} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode([
        'status' => 'error',
        'message' => 'Failed to process sale: ' . $e->getMessage()
    ]);
}