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

// For testing without session
if (!isset($_SESSION['user'])) {
    $_SESSION['user'] = [
        'id' => 1,
        'shop_id' => 1,
        'shop_name' => 'Test Shop',
        'fullname' => 'Test User'
    ];
}

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

echo "<h3>Manual Sale Test</h3>";
echo "<pre>";

try {
    // Start transaction
    $pdo->beginTransaction();
    
    echo "1. Getting test product...\n";
    $stmt = $pdo->prepare("SELECT id FROM products WHERE shop_id = ? AND is_active = 1 LIMIT 1");
    $stmt->execute([$shop_id]);
    $product = $stmt->fetch();
    
    if (!$product) {
        throw new Exception("No products found in shop $shop_id");
    }
    
    $product_id = $product['id'];
    echo "   Product ID: $product_id\n";
    
    echo "2. Getting available batch...\n";
    $stmt = $pdo->prepare("
        SELECT pb.id, pb.batch_no, bs.current_qty 
        FROM product_batches pb
        LEFT JOIN batch_stock_view bs ON pb.id = bs.batch_id
        WHERE pb.product_id = ? AND pb.shop_id = ? 
        AND (bs.current_qty > 0 OR bs.current_qty IS NULL)
        AND pb.is_active = 1
        LIMIT 1
    ");
    $stmt->execute([$product_id, $shop_id]);
    $batch = $stmt->fetch();
    
    if (!$batch) {
        throw new Exception("No batches available for product $product_id");
    }
    
    $batch_id = $batch['id'];
    $available_qty = $batch['current_qty'] ?? 0;
    echo "   Batch ID: $batch_id (Available: $available_qty)\n";
    
    echo "3. Generating invoice number...\n";
    $invoice_no = "TEST-" . date('Ymd-His') . "-" . rand(100, 999);
    echo "   Invoice: $invoice_no\n";
    
    echo "4. Creating sale record...\n";
    $total = 100.00; // Test amount
    $stmt = $pdo->prepare("
        INSERT INTO sales (invoice_no, sale_date, customer_id, total, paid, status, created_by, shop_id)
        VALUES (?, NOW(), NULL, ?, 100.00, 'paid', ?, ?)
    ");
    $stmt->execute([$invoice_no, $total, $user_id, $shop_id]);
    $sale_id = $pdo->lastInsertId();
    echo "   Sale ID: $sale_id\n";
    
    echo "5. Creating sale line...\n";
    $qty = 1;
    $price = 100.00;
    $line_total = $qty * $price;
    
    $stmt = $pdo->prepare("
        INSERT INTO sale_lines (sale_id, product_id, batch_id, qty, unit_price, discount, line_total, shop_id)
        VALUES (?, ?, ?, ?, ?, 0, ?, ?)
    ");
    $stmt->execute([$sale_id, $product_id, $batch_id, $qty, $price, $line_total, $shop_id]);
    echo "   Sale line created\n";
    
    echo "6. Creating inventory movement...\n";
    $stmt = $pdo->prepare("
        INSERT INTO inventory_movements (product_id, batch_id, change_qty, movement_type, reference_id, created_by, shop_id)
        VALUES (?, ?, ?, 'SALE', ?, ?, ?)
    ");
    $stmt->execute([$product_id, $batch_id, $qty, $sale_id, $user_id, $shop_id]);
    echo "   Inventory movement created\n";
    
    echo "7. Creating payment record...\n";
    $stmt = $pdo->prepare("
        INSERT INTO payments (sale_id, amount, method, paid_at, created_by, shop_id)
        VALUES (?, ?, 'CASH', NOW(), ?, ?)
    ");
    $stmt->execute([$sale_id, $total, $user_id, $shop_id]);
    echo "   Payment recorded\n";
    
    // Commit
    $pdo->commit();
    
    echo "\n✅ TEST SUCCESSFUL!\n";
    echo "Sale #$sale_id created successfully\n";
    
    // Verify
    echo "\n8. Verification:\n";
    $stmt = $pdo->prepare("SELECT * FROM sales WHERE id = ?");
    $stmt->execute([$sale_id]);
    $sale = $stmt->fetch();
    echo "   Sale total: " . $sale['total'] . "\n";
    echo "   Sale status: " . $sale['status'] . "\n";
    
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM sale_lines WHERE sale_id = ?");
    $stmt->execute([$sale_id]);
    $lines = $stmt->fetch();
    echo "   Sale lines: " . $lines['count'] . "\n";
    
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM inventory_movements WHERE reference_id = ? AND movement_type = 'SALE'");
    $stmt->execute([$sale_id]);
    $movements = $stmt->fetch();
    echo "   Inventory movements: " . $movements['count'] . "\n";
    
} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    echo "\n❌ TEST FAILED: " . $e->getMessage() . "\n";
    echo "Error details: " . $e->getTraceAsString() . "\n";
}

echo "</pre>";
echo "<hr>";
echo "<a href='debug_pos.php'>← Back to Debug</a>";
?>