<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requireLogin();

$user = currentUser();
$is_super_admin = $user['role_id'] == 1;
if (!$is_super_admin) {
    $_SESSION['error'] = 'Access denied.';
    header('Location: ' . getRedirectUrl()); exit;
}

$pdo = getDB();

// Internal dashboard data test - run queries directly
$dashboardJson = array('success' => false, 'message' => 'Not tested');
try {
    $test_data = array();

    $stmt = $pdo->query("SELECT COALESCE(SUM(total_amount), 0) FROM sales_invoices WHERE DATE(invoice_date) = CURDATE() AND invoice_status != 'Cancelled'");
    $test_data['today_sales'] = (float)$stmt->fetchColumn();

    $stmt = $pdo->query("SELECT COALESCE(SUM(amount), 0) FROM payments WHERE payment_type = 'repair' AND DATE(payment_date) = CURDATE()");
    $test_data['today_repair_income'] = (float)$stmt->fetchColumn();

    $stmt = $pdo->query("SELECT COUNT(*) FROM repair_jobs WHERE repair_status NOT IN ('Delivered','Cancelled','Cannot Repair')");
    $test_data['pending_repairs'] = (int)$stmt->fetchColumn();

    $stmt = $pdo->query("SELECT COUNT(*) FROM repair_jobs WHERE repair_status = 'Delivered'");
    $test_data['completed_repairs'] = (int)$stmt->fetchColumn();

    $stmt = $pdo->query("SELECT COUNT(*) FROM products WHERE current_stock <= low_stock_qty AND status = 1");
    $test_data['low_stock'] = (int)$stmt->fetchColumn();

    $stmt = $pdo->query("SELECT COUNT(*) FROM customers WHERE status = 1");
    $test_data['total_customers'] = (int)$stmt->fetchColumn();

    $stmt = $pdo->query("SELECT COUNT(*) FROM products WHERE status = 1");
    $test_data['total_products'] = (int)$stmt->fetchColumn();

    $stmt = $pdo->query("SELECT COUNT(*) FROM sales_invoices WHERE invoice_status != 'Cancelled'");
    $test_data['total_invoices'] = (int)$stmt->fetchColumn();

    $stmt = $pdo->query("SELECT COALESCE(SUM(amount), 0) FROM expenses WHERE DATE(expense_date) = CURDATE()");
    $test_data['today_expenses'] = (float)$stmt->fetchColumn();

    $dashboardJson = array('success' => true, 'stats' => $test_data);
} catch (Exception $e) {
    $dashboardJson = array('success' => false, 'message' => $e->getMessage());
}

$shop_logo_value = getSetting('shop_logo', '');
$logo_full_path = BASE_PATH . $shop_logo_value;
$logo_exists = !empty($shop_logo_value) && file_exists($logo_full_path);
$logo_url = getShopLogoUrl();

include BASE_PATH . 'includes/header.php';
include BASE_PATH . 'includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <h4 class="page-title"><i class="fas fa-bug me-2"></i>Debug: Logo & Dashboard</h4>

        <div class="card mb-3">
            <div class="card-header"><h5>Paths</h5></div>
            <div class="card-body">
                <table class="table table-bordered table-sm">
                    <tr><td>BASE_URL</td><td><code><?= htmlspecialchars(BASE_URL) ?></code></td></tr>
                    <tr><td>BASE_PATH</td><td><code><?= htmlspecialchars(BASE_PATH) ?></code></td></tr>
                    <tr><td>logo setting value</td><td><code><?= htmlspecialchars($shop_logo_value) ?></code></td></tr>
                    <tr><td>Full server path</td><td><code><?= htmlspecialchars($logo_full_path) ?></code></td></tr>
                    <tr><td>File exists</td><td><?= $logo_exists ? '<span class="text-success">Yes</span>' : '<span class="text-danger">No</span>' ?></td></tr>
                    <tr><td>Logo URL</td><td><code><?= htmlspecialchars($logo_url) ?></code></td></tr>
                </table>
                <div class="mt-2">
                    <strong>Logo Preview:</strong><br>
                    <img src="<?= htmlspecialchars($logo_url) ?>?v=<?= time() ?>" alt="Logo Preview" style="max-height:80px;border:1px solid #ddd;" onerror="this.onerror=null;this.parentNode.innerHTML+='<span class=\'text-danger\'> Broken image</span>'">
                </div>
            </div>
        </div>

        <div class="card mb-3">
            <div class="card-header"><h5>Dashboard AJAX Test</h5></div>
            <div class="card-body">
                <p>Endpoint URL: <code><?= htmlspecialchars(BASE_URL) ?>admin/dashboard_data.php</code></p>
                <p><a href="<?= BASE_URL ?>admin/dashboard_data.php" target="_blank" class="btn btn-sm btn-outline-primary">Open Endpoint Directly</a></p>

                <?php if ($dashboardJson === null): ?>
                    <div class="alert alert-danger">
                        <strong>Invalid JSON response.</strong>
                        <pre style="margin-top:10px;max-height:200px;overflow:auto;"><?= htmlspecialchars(substr($dashboardRaw, 0, 2000)) ?></pre>
                    </div>
                <?php elseif (!($dashboardJson['success'] ?? false)): ?>
                    <div class="alert alert-warning">
                        <strong>API returned error:</strong> <?= htmlspecialchars($dashboardJson['message'] ?? 'Unknown') ?>
                    </div>
                <?php else: ?>
                    <div class="alert alert-success">API returned success=true</div>

                    <h6>Stats:</h6>
                    <table class="table table-bordered table-sm">
                        <thead><tr><th>Key</th><th>Value</th></tr></thead>
                        <tbody>
                            <?php foreach ($dashboardJson['stats'] as $k => $v): ?>
                            <tr><td><code><?= htmlspecialchars($k) ?></code></td><td><?= htmlspecialchars(is_numeric($v) ? (string)$v : print_r($v, true)) ?></td></tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    <h6>Recent Sales: <?= count($dashboardJson['recent_sales'] ?? []) ?> rows</h6>
                    <h6>Recent Repairs: <?= count($dashboardJson['recent_repairs'] ?? []) ?> rows</h6>
                    <h6>Low Stock Products: <?= count($dashboardJson['low_stock_products'] ?? []) ?> rows</h6>
                <?php endif; ?>
            </div>
        </div>

        <div class="card mb-3">
            <div class="card-header"><h5>Database Record Counts</h5></div>
            <div class="card-body">
                <table class="table table-bordered table-sm">
                    <?php
                    foreach (['sales_invoices','repair_jobs','products','customers','suppliers','payments','expenses','purchases'] as $tbl):
                        $cnt = $pdo->query("SELECT COUNT(*) FROM $tbl")->fetchColumn();
                    ?>
                    <tr><td><code><?= $tbl ?></code></td><td><?= $cnt ?></td></tr>
                    <?php endforeach; ?>
                </table>
            </div>
        </div>

        <div class="card">
            <div class="card-header"><h5>Settings Table (all rows)</h5></div>
            <div class="card-body">
                <table class="table table-bordered table-sm">
                    <thead><tr><th>setting_key</th><th>setting_value</th><th>setting_group</th></tr></thead>
                    <tbody>
                        <?php foreach ($pdo->query("SELECT setting_key, setting_value, setting_group FROM settings ORDER BY setting_key") as $s): ?>
                        <tr><td><code><?= htmlspecialchars($s['setting_key']) ?></code></td><td><?= htmlspecialchars($s['setting_value']) ?></td><td><?= htmlspecialchars($s['setting_group']) ?></td></tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<?php include BASE_PATH . 'includes/footer.php'; ?>
