<?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();

// Permission checks
$perms = $pdo->query("SELECT p.permission_key, p.permission_name, rp.role_id FROM permissions p LEFT JOIN role_permissions rp ON p.id = rp.permission_id AND rp.role_id = 4 ORDER BY p.id")->fetchAll();

// Jobs with/without technician
$total_jobs = $pdo->query("SELECT COUNT(*) FROM repair_jobs")->fetchColumn();
$assigned_jobs = $pdo->query("SELECT COUNT(*) FROM repair_jobs WHERE assigned_technician_id IS NOT NULL")->fetchColumn();
$unassigned_jobs = $pdo->query("SELECT COUNT(*) FROM repair_jobs WHERE assigned_technician_id IS NULL")->fetchColumn();

// Technician users
$techs = $pdo->query("SELECT u.id, u.name, u.email, r.role_name FROM users u JOIN roles r ON u.role_id = r.id WHERE r.role_name = 'Technician' OR u.id IN (SELECT assigned_technician_id FROM repair_jobs WHERE assigned_technician_id IS NOT NULL)")->fetchAll();

// Technician role permissions
$tech_role_perms = $pdo->query("SELECT p.permission_key, p.permission_name FROM role_permissions rp JOIN permissions p ON rp.permission_id = p.id WHERE rp.role_id = 4")->fetchAll();

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>Technician Panel Debug</h4>

        <div class="card mb-3">
            <div class="card-header"><h5>Current User</h5></div>
            <div class="card-body">
                <pre><?php print_r($user); ?></pre>
            </div>
        </div>

        <div class="card mb-3">
            <div class="card-header"><h5>Repair Jobs Overview</h5></div>
            <div class="card-body">
                <table class="table table-bordered">
                    <tr><td>Total Jobs</td><td><?= $total_jobs ?></td></tr>
                    <tr><td>Assigned to Technician</td><td><?= $assigned_jobs ?></td></tr>
                    <tr><td>Unassigned</td><td><?= $unassigned_jobs ?></td></tr>
                </table>
            </div>
        </div>

        <div class="card mb-3">
            <div class="card-header"><h5>Technicians & Users with Assigned Jobs</h5></div>
            <div class="card-body">
                <table class="table table-bordered table-sm">
                    <thead><tr><th>ID</th><th>Name</th><th>Email</th><th>Role</th></tr></thead>
                    <tbody>
                        <?php foreach ($techs as $t): ?>
                        <tr><td><?= $t['id'] ?></td><td><?= htmlspecialchars($t['name'] ?? '') ?></td><td><?= htmlspecialchars($t['email'] ?? '') ?></td><td><?= htmlspecialchars($t['role_name'] ?? '') ?></td></tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="card mb-3">
            <div class="card-header"><h5>Technician Role Permissions (role_id=4)</h5></div>
            <div class="card-body">
                <?php if (count($tech_role_perms) > 0): ?>
                <ul><?php foreach ($tech_role_perms as $p): ?><li><code><?= htmlspecialchars($p['permission_key']) ?></code> — <?= htmlspecialchars($p['permission_name']) ?></li><?php endforeach; ?></ul>
                <?php else: ?><p class="text-danger">No permissions assigned to Technician role!</p><?php endif; ?>
            </div>
        </div>

        <div class="card mb-3">
            <div class="card-header"><h5>All Permission Assignments for Role ID 4 (Technician)</h5></div>
            <div class="card-body">
                <table class="table table-bordered table-sm">
                    <thead><tr><th>Permission Key</th><th>Permission Name</th><th>Has Role 4?</th></tr></thead>
                    <tbody>
                        <?php
                        $seen = [];
                        foreach ($perms as $p):
                            $key = $p['permission_key'];
                            if (in_array($key, $seen)) continue;
                            $seen[] = $key;
                            $has_perm = !is_null($p['role_id']);
                        ?>
                        <tr class="<?= $has_perm ? 'table-success' : 'table-danger' ?>">
                            <td><code><?= htmlspecialchars($key) ?></code></td>
                            <td><?= htmlspecialchars($p['permission_name'] ?? '') ?></td>
                            <td><?= $has_perm ? 'Yes' : 'No' ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="card mb-3">
            <div class="card-header"><h5>File Existence Check</h5></div>
            <div class="card-body">
                <table class="table table-bordered table-sm">
                    <?php
                    $files = [
                        'technician_panel.php',
                        'update_job_status.php',
                        '../config/auth.php',
                        '../includes/functions.php',
                        '../includes/header.php',
                        '../includes/sidebar.php',
                        '../includes/footer.php',
                        '../config/config.php',
                        '../config/database.php',
                    ];
                    foreach ($files as $f):
                        $exists = file_exists(__DIR__ . '/' . $f);
                    ?>
                    <tr class="<?= $exists ? 'table-success' : 'table-danger' ?>">
                        <td><code>repairs/<?= $f ?></code></td>
                        <td><?= $exists ? 'EXISTS' : 'MISSING' ?></td>
                    </tr>
                    <?php endforeach; ?>
                </table>
            </div>
        </div>

        <div class="card mb-3">
            <div class="card-header"><h5>repair_job_parts and repair_job_status_history Tables</h5></div>
            <div class="card-body">
                <?php
                $parts_count = $pdo->query("SELECT COUNT(*) FROM repair_job_parts")->fetchColumn();
                $hist_count = $pdo->query("SELECT COUNT(*) FROM repair_job_status_history")->fetchColumn();
                ?>
                <p>repair_job_parts: <?= $parts_count ?> records</p>
                <p>repair_job_status_history: <?= $hist_count ?> records</p>
            </div>
        </div>

        <div class="card">
            <div class="card-header"><h5>All Repair Jobs</h5></div>
            <div class="card-body">
                <?php
                $all_jobs = $pdo->query("SELECT rj.id, rj.job_no, rj.repair_status, rj.assigned_technician_id, COALESCE(u.name, 'Unassigned') as tech_name, rj.is_demo FROM repair_jobs rj LEFT JOIN users u ON rj.assigned_technician_id = u.id ORDER BY rj.id")->fetchAll();
                ?>
                <table class="table table-bordered table-sm">
                    <thead><tr><th>ID</th><th>Job No</th><th>Status</th><th>Technician</th><th>Is Demo</th></tr></thead>
                    <tbody>
                        <?php foreach ($all_jobs as $j): ?>
                        <tr>
                            <td><?= $j['id'] ?></td>
                            <td><?= htmlspecialchars($j['job_no']) ?></td>
                            <td><?= getStatusBadge($j['repair_status']) ?></td>
                            <td><?= htmlspecialchars($j['tech_name']) ?></td>
                            <td><?= $j['is_demo'] ? 'Yes' : 'No' ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<?php include BASE_PATH . 'includes/footer.php'; ?>
