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

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

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Log file
file_put_contents('sale_debug.log', "\n=== NEW REQUEST " . date('Y-m-d H:i:s') . " ===\n", FILE_APPEND);

// Check if user is logged in
if (!isset($_SESSION['user']['id']) || !isset($_SESSION['user']['shop_id'])) {
    $response = [
        'status' => 'error', 
        'message' => 'User not logged in or session expired. Please login again.',
        'debug' => ['session' => $_SESSION]
    ];
    file_put_contents('sale_debug.log', "SESSION ERROR: " . print_r($response, true) . "\n", FILE_APPEND);
    echo json_encode($response);
    exit;
}

// Get user data
$shop_id = (int)$_SESSION['user']['shop_id'];
$user_id = (int)$_SESSION['user']['id'];
$shop_name = $_SESSION['user']['shop_name'] ?? 'Shop';

file_put_contents('sale_debug.log', "User: $user_id, Shop: $shop_id ($shop_name)\n", FILE_APPEND);
file_put_contents('sale_debug.log', "POST Data: " . print_r($_POST, true) . "\n", FILE_APPEND);

// Check if request is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response = [
        'status' => 'error', 
        'message' => 'Invalid request method. Use POST.',
        'debug' => ['method' => $_SERVER['REQUEST_METHOD']]
    ];
    echo json_encode($response);
    exit;
}

// Get POST data
$customer_id = isset($_POST['customer_id']) && $_POST['customer_id'] != '' ? (int)$_POST['customer_id'] : null;
$new_customer_name = trim($_POST['new_customer_name'] ?? '');
$new_customer_phone = trim($_POST['new_customer_phone'] ?? '');
$new_customer_email = trim($_POST['new_customer_email'] ?? '');
$new_customer_address = trim($_POST['new_customer_address'] ?? '');
$payment_method = $_POST['payment_method'] ?? 'CASH';
$paid = isset($_POST['paid']) ? (float)$_POST['paid'] : 0;
$items = $_POST['items'] ?? [];

// Validate items
if (empty($items)) {
    $response = [
        'status' => 'error', 
        'message' => 'No items in cart. Please add products before completing sale.',
        'debug' => ['items_received' => $items]
    ];
    file_put_contents('sale_debug.log', "NO ITEMS ERROR: " . print_r($response, true) . "\n", FILE_APPEND);
    echo json_encode($response);
    exit;
}

// Validate payment method
$allowed_methods = ['CASH', 'CARD', 'M-PESA', 'TIGO-PESA', 'AIRTEL-MONEY'];
if (!in_array($payment_method, $allowed_methods)) {
    $payment_method = 'CASH';
}

try {
    // Start transaction
    $pdo->beginTransaction();
    file_put_contents('sale_debug.log', "Transaction started\n", FILE_APPEND);
    
    // 1. Handle customer
    $final_customer_id = null;
    
    if (!empty($new_customer_name) && !$customer_id) {
        // Create new customer
        file_put_contents('sale_debug.log', "Creating new customer: $new_customer_name\n", FILE_APPEND);
        
        $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' => $new_customer_name,
            ':phone' => !empty($new_customer_phone) ? $new_customer_phone : null,
            ':email' => !empty($new_customer_email) ? $new_customer_email : null,
            ':address' => !empty($new_customer_address) ? $new_customer_address : null
        ]);
        
        $final_customer_id = $pdo->lastInsertId();
        file_put_contents('sale_debug.log', "New customer ID: $final_customer_id\n", FILE_APPEND);
        
    } elseif ($customer_id) {
        // Use existing customer
        $final_customer_id = $customer_id;
        file_put_contents('sale_debug.log', "Using existing customer ID: $final_customer_id\n", FILE_APPEND);
    } else {
        // Walk-in customer (null)
        file_put_contents('sale_debug.log', "No customer specified (walk-in)\n", FILE_APPEND);
    }
    
    // 2. Generate invoice number
    $year = date('Y');
    $month = date('m');
    $day = date('d');
    $random = str_pad(mt_rand(1, 999), 3, '0', STR_PAD_LEFT);
    $invoice_no = "SHOP{$shop_id}-{$year}{$month}{$day}-{$random}";
    
    file_put_contents('sale_debug.log', "Generated invoice: $invoice_no\n", FILE_APPEND);
    
    // 3. Calculate total from items
    $total = 0;
    $item_details = [];
    
    foreach ($items as $index => $item) {
        $qty = (int)($item['qty'] ?? 0);
        $unit_price = (float)($item['unit_price'] ?? 0);
        $discount = (float)($item['discount'] ?? 0);
        $item_total = ($qty * $unit_price) - $discount;
        $total += $item_total;
        
        $item_details[] = [
            'index' => $index,
            'qty' => $qty,
            'price' => $unit_price,
            'discount' => $discount,
            'total' => $item_total
        ];
        
        file_put_contents('sale_debug.log', "Item $index: $qty × $unit_price - $discount = $item_total\n", FILE_APPEND);
    }
    
    file_put_contents('sale_debug.log', "Total calculated: $total\n", FILE_APPEND);
    
    // 4. Determine payment status
    $status = 'open';
    if ($paid >= $total) {
        $status = 'paid';
    } elseif ($paid > 0) {
        $status = 'partially_paid';
    }
    
    file_put_contents('sale_debug.log', "Payment status: $status (paid: $paid, total: $total)\n", FILE_APPEND);
    
    // 5. 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
        )
    ");
    
    $stmt->execute([
        ':invoice_no' => $invoice_no,
        ':customer_id' => $final_customer_id,
        ':total' => $total,
        ':paid' => $paid,
        ':status' => $status,
        ':created_by' => $user_id,
        ':shop_id' => $shop_id
    ]);
    
    $sale_id = $pdo->lastInsertId();
    file_put_contents('sale_debug.log', "Sale created with ID: $sale_id\n", FILE_APPEND);
    
    // 6. Insert sale lines and update inventory
    foreach ($items as $index => $item) {
        $product_id = (int)($item['product_id'] ?? 0);
        $batch_id = (int)($item['batch_id'] ?? 0);
        $qty = (int)($item['qty'] ?? 0);
        $unit_price = (float)($item['unit_price'] ?? 0);
        $discount = (float)($item['discount'] ?? 0);
        $line_total = ($qty * $unit_price) - $discount;
        
        file_put_contents('sale_debug.log', "Processing sale line - Product: $product_id, Batch: $batch_id, Qty: $qty\n", FILE_APPEND);
        
        // Check if batch exists
        $check_batch = $pdo->prepare("SELECT id FROM product_batches WHERE id = :batch_id AND shop_id = :shop_id");
        $check_batch->execute([':batch_id' => $batch_id, ':shop_id' => $shop_id]);
        
        if (!$check_batch->fetch()) {
            throw new Exception("Batch $batch_id not found or doesn't belong to shop $shop_id");
        }
        
        // 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' => $product_id,
            ':batch_id' => $batch_id,
            ':qty' => $qty,
            ':unit_price' => $unit_price,
            ':discount' => $discount,
            ':line_total' => $line_total,
            ':shop_id' => $shop_id
        ]);
        
        file_put_contents('sale_debug.log', "Sale line inserted for batch $batch_id\n", FILE_APPEND);
        
        // Create inventory movement
        $stmt = $pdo->prepare("
            INSERT INTO inventory_movements (
                product_id, batch_id, change_qty, movement_type, 
                reference_id, created_by, shop_id
            ) VALUES (
                :product_id, :batch_id, :change_qty, 'SALE',
                :reference_id, :created_by, :shop_id
            )
        ");
        
        $stmt->execute([
            ':product_id' => $product_id,
            ':batch_id' => $batch_id,
            ':change_qty' => $qty,
            ':reference_id' => $sale_id,
            ':created_by' => $user_id,
            ':shop_id' => $shop_id
        ]);
        
        file_put_contents('sale_debug.log', "Inventory movement created (deducted $qty from batch $batch_id)\n", FILE_APPEND);
    }
    
    // 7. Insert payment record if any amount paid
    if ($paid > 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,
            ':method' => $payment_method,
            ':created_by' => $user_id,
            ':shop_id' => $shop_id
        ]);
        
        file_put_contents('sale_debug.log', "Payment recorded: $paid via $payment_method\n", FILE_APPEND);
    }
    
    // 8. Commit transaction
    $pdo->commit();
    
    file_put_contents('sale_debug.log', "=== SALE COMPLETED SUCCESSFULLY ===\n", FILE_APPEND);
    file_put_contents('sale_debug.log', "Sale ID: $sale_id, Invoice: $invoice_no, Total: $total, Status: $status\n", FILE_APPEND);
    
    // Return success response
    $response = [
        'status' => 'success',
        'message' => 'Sale completed successfully!',
        'sale_id' => $sale_id,
        'invoice_no' => $invoice_no,
        'details' => [
            'total' => number_format($total, 2),
            'status' => $status,
            'paid' => number_format($paid, 2),
            'balance' => number_format($total - $paid, 2),
            'items_count' => count($items)
        ],
        'redirect_url' => "view_sale.php?id=$sale_id"
    ];
    
    echo json_encode($response);
    
} catch (PDOException $e) {
    // Rollback on error
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    file_put_contents('sale_debug.log', "DATABASE ERROR: " . $e->getMessage() . "\n", FILE_APPEND);
    file_put_contents('sale_debug.log', "TRACE: " . $e->getTraceAsString() . "\n", FILE_APPEND);
    
    $response = [
        'status' => 'error',
        'message' => 'Database error occurred. Please try again.',
        'debug' => $e->getMessage(),
        'code' => $e->getCode()
    ];
    
    echo json_encode($response);
    
} catch (Exception $e) {
    // Rollback on error
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    file_put_contents('sale_debug.log', "GENERAL ERROR: " . $e->getMessage() . "\n", FILE_APPEND);
    
    $response = [
        'status' => 'error',
        'message' => 'Error: ' . $e->getMessage()
    ];
    
    echo json_encode($response);
}

file_put_contents('sale_debug.log', "=== REQUEST COMPLETED ===\n\n", FILE_APPEND);
?>