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

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

// Check if PDO connection exists
if (!isset($pdo)) {
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit;
}

// Validate user session
if (!isset($_SESSION['user']['shop_id']) || !isset($_SESSION['user']['id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

$shop_id = (int)$_SESSION['user']['shop_id'];
$user_id = (int)$_SESSION['user']['id'];

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

// For form data (if not using JSON)
if (empty($data)) {
    $data = $_POST;
    if (isset($data['cart'])) {
        $data['cart'] = json_decode($data['cart'], true);
    }
}

// Validate required data
if (empty($data['cart']) || !is_array($data['cart'])) {
    echo json_encode(['success' => false, 'message' => 'Cart is empty']);
    exit;
}

try {
    // Start transaction
    $pdo->beginTransaction();
    
    // Create or get customer
    $customer_id = null;
    if (!empty($data['customer_id'])) {
        $customer_id = (int)$data['customer_id'];
    } elseif (!empty($data['new_customer_name'])) {
        // Insert new customer
        $stmt = $pdo->prepare("
            INSERT INTO customers (shop_id, name, phone, email, address, created_at) 
            VALUES (:shop_id, :name, :phone, :email, :address, NOW())
        ");
        $stmt->execute([
            ':shop_id' => $shop_id,
            ':name' => trim($data['new_customer_name']),
            ':phone' => $data['new_customer_phone'] ?? '',
            ':email' => $data['new_customer_email'] ?? '',
            ':address' => $data['new_customer_address'] ?? ''
        ]);
        $customer_id = $pdo->lastInsertId();
    }
    
    // Calculate totals
    $subtotal = 0;
    $vat_total = 0;
    $grand_total = 0;
    
    foreach ($data['cart'] as $item) {
        $line_total = $item['qty'] * $item['unit_price'];
        $discount_amount = $line_total * ($item['discount'] / 100);
        $after_discount = $line_total - $discount_amount;
        $vat_amount = $after_discount * ($item['vat_percent'] / 100);
        
        $subtotal += $after_discount;
        $vat_total += $vat_amount;
        $grand_total += ($after_discount + $vat_amount);
    }
    
    // Insert sale record
    $stmt = $pdo->prepare("
        INSERT INTO sales (
            invoice_no, 
            sale_date, 
            customer_id, 
            total, 
            paid, 
            status, 
            created_by, 
            shop_id
        ) VALUES (
            :invoice_no,
            NOW(),
            :customer_id,
            :total,
            :paid,
            :status,
            :created_by,
            :shop_id
        )
    ");
    
    $paid_amount = (float)($data['amount_paid'] ?? 0);
    $status = $paid_amount >= $grand_total ? 'paid' : 
              ($paid_amount > 0 ? 'partially_paid' : 'open');
    
    $stmt->execute([
        ':invoice_no' => $data['invoice_no'] ?? ('SALE-' . date('Ymd-His') . '-' . rand(100, 999)),
        ':customer_id' => $customer_id,
        ':total' => $grand_total,
        ':paid' => $paid_amount,
        ':status' => $status,
        ':created_by' => $user_id,
        ':shop_id' => $shop_id
    ]);
    
    $sale_id = $pdo->lastInsertId();
    
    // Insert sale lines and update inventory
    foreach ($data['cart'] as $item) {
        // Calculate line totals
        $line_total = $item['qty'] * $item['unit_price'];
        $discount_amount = $line_total * ($item['discount'] / 100);
        $after_discount = $line_total - $discount_amount;
        $vat_amount = $after_discount * ($item['vat_percent'] / 100);
        $final_total = $after_discount + $vat_amount;
        
        // Insert sale line
        $stmt = $pdo->prepare("
            INSERT INTO sale_lines (
                sale_id,
                product_id,
                batch_id,
                qty,
                unit_price,
                discount,
                line_total,
                shop_id
            ) VALUES (
                :sale_id,
                :product_id,
                :batch_id,
                :qty,
                :unit_price,
                :discount,
                :line_total,
                :shop_id
            )
        ");
        
        $stmt->execute([
            ':sale_id' => $sale_id,
            ':product_id' => $item['product_id'],
            ':batch_id' => $item['batch_id'],
            ':qty' => $item['qty'],
            ':unit_price' => $item['unit_price'],
            ':discount' => $item['discount'],
            ':line_total' => $final_total,
            ':shop_id' => $shop_id
        ]);
        
        // Create inventory movement (deduct stock)
        $stmt = $pdo->prepare("
            INSERT INTO inventory_movements (
                product_id,
                batch_id,
                change_qty,
                movement_type,
                reference_id,
                created_by,
                shop_id,
                created_at
            ) VALUES (
                :product_id,
                :batch_id,
                :change_qty,
                'SALE',
                :reference_id,
                :created_by,
                :shop_id,
                NOW()
            )
        ");
        
        $stmt->execute([
            ':product_id' => $item['product_id'],
            ':batch_id' => $item['batch_id'],
            ':change_qty' => $item['qty'],
            ':reference_id' => $sale_id,
            ':created_by' => $user_id,
            ':shop_id' => $shop_id
        ]);
    }
    
    // Insert payment if paid
    if ($paid_amount > 0) {
        $stmt = $pdo->prepare("
            INSERT INTO payments (
                sale_id,
                amount,
                method,
                paid_at,
                created_by,
                shop_id
            ) VALUES (
                :sale_id,
                :amount,
                :method,
                NOW(),
                :created_by,
                :shop_id
            )
        ");
        
        $stmt->execute([
            ':sale_id' => $sale_id,
            ':amount' => $paid_amount,
            ':method' => $data['payment_method'] ?? 'CASH',
            ':created_by' => $user_id,
            ':shop_id' => $shop_id
        ]);
    }
    
    // Commit transaction
    $pdo->commit();
    
    // Get invoice number for response
    $stmt = $pdo->prepare("SELECT invoice_no FROM sales WHERE id = :sale_id");
    $stmt->execute([':sale_id' => $sale_id]);
    $sale = $stmt->fetch();
    
    echo json_encode([
        'success' => true,
        'sale_id' => $sale_id,
        'invoice_no' => $sale['invoice_no'],
        'total' => $grand_total,
        'paid' => $paid_amount,
        'change' => $paid_amount - $grand_total,
        'message' => 'Sale completed successfully'
    ]);
    
} catch (PDOException $e) {
    // Rollback on error
    $pdo->rollBack();
    error_log("Save sale error: " . $e->getMessage());
    echo json_encode([
        'success' => false, 
        'message' => 'Failed to save sale: ' . $e->getMessage()
    ]);
} catch (Exception $e) {
    $pdo->rollBack();
    error_log("Save sale error: " . $e->getMessage());
    echo json_encode([
        'success' => false, 
        'message' => 'An error occurred: ' . $e->getMessage()
    ]);
}
?>