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

// Debug mode
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<h3>POS System Debug</h3>";
echo "<hr>";

// 1. Check session
echo "<h4>1. Session Check:</h4>";
if (isset($_SESSION['user'])) {
    echo "<pre>Session User Data: " . print_r($_SESSION['user'], true) . "</pre>";
    echo "<span style='color:green'>✓ Session OK</span><br>";
    echo "User ID: " . $_SESSION['user']['id'] . "<br>";
    echo "Shop ID: " . $_SESSION['user']['shop_id'] . "<br>";
} else {
    echo "<span style='color:red'>✗ No session found</span><br>";
}

echo "<hr>";

// 2. Check database connection
echo "<h4>2. Database Check:</h4>";
try {
    $pdo->query("SELECT 1");
    echo "<span style='color:green'>✓ Database connection OK</span><br>";
    
    // Test basic queries
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM products WHERE shop_id = " . $_SESSION['user']['shop_id']);
    $product_count = $stmt->fetch()['count'];
    echo "Products in shop: $product_count<br>";
    
} catch (PDOException $e) {
    echo "<span style='color:red'>✗ Database error: " . $e->getMessage() . "</span><br>";
}

echo "<hr>";

// 3. Check required tables
echo "<h4>3. Table Structure Check:</h4>";
$tables = ['products', 'product_batches', 'sales', 'sale_lines', 'inventory_movements'];
foreach ($tables as $table) {
    try {
        $stmt = $pdo->query("SHOW COLUMNS FROM $table");
        $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);
        echo "<span style='color:green'>✓ $table (" . count($columns) . " columns)</span><br>";
    } catch (Exception $e) {
        echo "<span style='color:red'>✗ $table: " . $e->getMessage() . "</span><br>";
    }
}

echo "<hr>";

// 4. Test inventory movement trigger
echo "<h4>4. Trigger Test:</h4>";
try {
    $stmt = $pdo->query("SHOW TRIGGERS LIKE 'inventory_movements'");
    $triggers = $stmt->fetchAll();
    if (count($triggers) > 0) {
        echo "<span style='color:green'>✓ Inventory triggers exist</span><br>";
        foreach ($triggers as $trigger) {
            echo "Trigger: " . $trigger['Trigger'] . " (" . $trigger['Timing'] . " " . $trigger['Event'] . ")<br>";
        }
    } else {
        echo "<span style='color:orange'>⚠ No triggers found on inventory_movements</span><br>";
    }
} catch (Exception $e) {
    echo "<span style='color:red'>✗ Trigger check error: " . $e->getMessage() . "</span><br>";
}

echo "<hr>";

// 5. Test sale process manually
echo "<h4>5. Manual Sale Test:</h4>";
if (isset($_SESSION['user']['shop_id'])) {
    echo "<form method='post' action='test_sale.php'>
        <input type='hidden' name='test' value='1'>
        <button type='submit'>Run Manual Sale Test</button>
    </form>";
}

echo "<hr>";

// 6. Check AJAX endpoints
echo "<h4>6. AJAX Endpoints:</h4>";
$endpoints = [
    'search_product.php',
    'get_product_batches.php',
    'save_sale.php',
    'test_connection.php'
];

foreach ($endpoints as $endpoint) {
    if (file_exists($endpoint)) {
        echo "<span style='color:green'>✓ $endpoint exists</span><br>";
    } else {
        echo "<span style='color:red'>✗ $endpoint missing</span><br>";
    }
}

echo "<hr>";

// 7. JavaScript test
echo "<h4>7. JavaScript Test:</h4>";
echo <<<HTML
<button onclick="testJS()">Test JavaScript</button>
<button onclick="testAjax()">Test AJAX</button>
<div id="testResult"></div>

<script>
function testJS() {
    document.getElementById('testResult').innerHTML = 'JavaScript is working!';
}

function testAjax() {
    fetch('test_connection.php')
        .then(response => response.json())
        .then(data => {
            document.getElementById('testResult').innerHTML = 'AJAX Test: ' + JSON.stringify(data);
        })
        .catch(error => {
            document.getElementById('testResult').innerHTML = 'AJAX Error: ' + error;
        });
}
</script>
HTML;

echo "<hr>";

// 8. File permissions check
echo "<h4>8. File Permissions:</h4>";
$log_file = 'sale_debug.log';
if (file_exists($log_file)) {
    $size = filesize($log_file);
    $writable = is_writable($log_file);
    echo "Log file: $log_file<br>";
    echo "Size: " . ($size / 1024) . " KB<br>";
    echo "Writable: " . ($writable ? "✓ Yes" : "✗ No") . "<br>";
    
    if ($size > 0) {
        echo "Last 10 lines of log:<br><pre>";
        $lines = file($log_file);
        $last_lines = array_slice($lines, -10);
        echo implode("", $last_lines);
        echo "</pre>";
    }
} else {
    echo "<span style='color:orange'>⚠ Log file not found</span><br>";
    // Try to create it
    if (touch($log_file)) {
        echo "<span style='color:green'>✓ Created log file</span><br>";
    } else {
        echo "<span style='color:red'>✗ Cannot create log file</span><br>";
    }
}
?>