<?php
session_start();
include_once('../includes/config.php');

// Check if user is logged in
if (!isset($_SESSION['uid'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Set content type to JSON
header('Content-Type: application/json');

try {
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        throw new Exception('Invalid JSON input');
    }
    
    // Validate required fields
    if (!isset($input['customer_id']) || !isset($input['cart_items']) || empty($input['cart_items'])) {
        throw new Exception('Customer ID and cart items are required');
    }
    
    $customerId = (int)$input['customer_id'];
    $paymentMethod = isset($input['payment_method']) ? $input['payment_method'] : 'Cash';
    $amountReceived = isset($input['amount_received']) ? (float)$input['amount_received'] : 0;
    $referenceNumber = isset($input['reference_number']) ? $input['reference_number'] : '';
    $notes = isset($input['notes']) ? $input['notes'] : '';
    $cartItems = $input['cart_items'];
    $userId = $_SESSION['uid'];
    
    // Start transaction
    mysqli_autocommit($con, false);
    
    try {
        $totalAmount = 0;
        $saleDate = date('Y-m-d');
        
        // Calculate total amount and validate stock
        foreach ($cartItems as $item) {
            $productId = (int)$item['product_id'];
            $quantity = (float)$item['quantity'];
            $rate = (float)$item['rate'];
            
            // Check current stock
            $stockQuery = "SELECT CurrentStock FROM tblricebags WHERE ID = $productId AND IsActive = 1";
            $stockResult = mysqli_query($con, $stockQuery);
            
            if (!$stockResult || mysqli_num_rows($stockResult) == 0) {
                throw new Exception("Product ID $productId not found");
            }
            
            $stockRow = mysqli_fetch_assoc($stockResult);
            $currentStock = (float)$stockRow['CurrentStock'];
            
            if ($quantity > $currentStock) {
                throw new Exception("Insufficient stock for product ID $productId");
            }
            
            $totalAmount += $rate * $quantity;
        }
        
        // Create payment record (Debit entry for sale)
        $paymentQuery = "
            INSERT INTO tblcustomerpayments 
            (CustomerID, TransactionType, Amount, PaymentMethod, ReferenceNumber, TransactionDate, Description, Status, CreatedBy, CreatedDate) 
            VALUES 
            ($customerId, 'Debit', $totalAmount, '$paymentMethod', '$referenceNumber', '$saleDate', 'POS Sale - $notes', 'Completed', $userId, NOW())
        ";
        
        if (!mysqli_query($con, $paymentQuery)) {
            throw new Exception('Failed to create payment record: ' . mysqli_error($con));
        }
        
        $paymentId = mysqli_insert_id($con);
        
        // If amount received is different from total, create a credit entry for payment received
        if ($amountReceived > 0 && $amountReceived != $totalAmount) {
            $paymentReceivedQuery = "
                INSERT INTO tblcustomerpayments 
                (CustomerID, TransactionType, Amount, PaymentMethod, ReferenceNumber, TransactionDate, Description, Status, CreatedBy, CreatedDate) 
                VALUES 
                ($customerId, 'Credit', $amountReceived, '$paymentMethod', '$referenceNumber', '$saleDate', 'Payment Received - POS Sale', 'Completed', $userId, NOW())
            ";
            
            if (!mysqli_query($con, $paymentReceivedQuery)) {
                throw new Exception('Failed to create payment received record: ' . mysqli_error($con));
            }
        } elseif ($amountReceived > 0 && $amountReceived == $totalAmount) {
            // Full payment received, create credit entry
            $paymentReceivedQuery = "
                INSERT INTO tblcustomerpayments 
                (CustomerID, TransactionType, Amount, PaymentMethod, ReferenceNumber, TransactionDate, Description, Status, CreatedBy, CreatedDate) 
                VALUES 
                ($customerId, 'Credit', $amountReceived, '$paymentMethod', '$referenceNumber', '$saleDate', 'Full Payment - POS Sale', 'Completed', $userId, NOW())
            ";
            
            if (!mysqli_query($con, $paymentReceivedQuery)) {
                throw new Exception('Failed to create payment received record: ' . mysqli_error($con));
            }
        }
        
        // Update stock for each item and create stock adjustment records
        foreach ($cartItems as $item) {
            $productId = (int)$item['product_id'];
            $quantity = (float)$item['quantity'];
            
            // Get current stock again (for accurate previous stock in adjustment)
            $stockQuery = "SELECT CurrentStock FROM tblricebags WHERE ID = $productId";
            $stockResult = mysqli_query($con, $stockQuery);
            $stockRow = mysqli_fetch_assoc($stockResult);
            $previousStock = (float)$stockRow['CurrentStock'];
            $newStock = $previousStock - $quantity;
            
            // Update product stock
            $updateStockQuery = "UPDATE tblricebags SET CurrentStock = $newStock WHERE ID = $productId";
            if (!mysqli_query($con, $updateStockQuery)) {
                throw new Exception('Failed to update stock for product ID ' . $productId);
            }
            
            // Create stock adjustment record
            $refNumber = 'SALE-' . date('dmy') . '-' . $paymentId;
            $adjustmentQuery = "
                INSERT INTO tblstockadjustments 
                (RiceBagID, AdjustmentType, Quantity, PreviousStock, NewStock, Reason, ReferenceNumber, AdjustmentDate, Status, CreatedBy, CreatedDate) 
                VALUES 
                ($productId, 'Remove', $quantity, $previousStock, $newStock, 'POS Sale', '$refNumber', '$saleDate', 'Approved', $userId, NOW())
            ";
            
            if (!mysqli_query($con, $adjustmentQuery)) {
                throw new Exception('Failed to create stock adjustment record');
            }
        }
        
        // Commit transaction
        mysqli_commit($con);
        
        echo json_encode([
            'success' => true,
            'message' => 'Sale completed successfully',
            'payment_id' => $paymentId,
            'total_amount' => $totalAmount,
            'amount_received' => $amountReceived
        ]);
        
    } catch (Exception $e) {
        // Rollback transaction
        mysqli_rollback($con);
        throw $e;
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
} finally {
    // Restore autocommit
    mysqli_autocommit($con, true);
}
?>
