<?php
// job_logs.php
header('Content-Type: text/html; charset=utf-8');
require 'db.php';
require 'auth.php';

require_login();
$user = current_user();

// Sadece admin + çağrı merkezi görsün (istersen role [1] yapıp sadece admin de bırakabilirsin)
if (!in_array($user['role'], [1,2], true)) {
    die("Bu sayfaya erişim yetkiniz yok.");
}

// Filtreler
$jobId   = isset($_GET['job_id']) ? (int)$_GET['job_id'] : 0;
$userId  = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;
$actionF = trim($_GET['action'] ?? '');
$dateF   = trim($_GET['date'] ?? ''); // YYYY-MM-DD

$conditions = [];
$params     = [];

$sql = "
    SELECT 
        l.*,
        u.name  AS user_name,
        u.role  AS user_role,
        j.title AS job_title,
        j.customer_name
    FROM job_logs l
    LEFT JOIN users u ON l.user_id = u.id
    LEFT JOIN jobs  j ON l.job_id = j.id
";


// Filtreleri ekle
if ($jobId > 0) {
    $conditions[] = "l.job_id = ?";
    $params[] = $jobId;
}
if ($userId > 0) {
    $conditions[] = "l.user_id = ?";
    $params[] = $userId;
}
if ($actionF !== '') {
    $conditions[] = "l.action = ?";
    $params[] = $actionF;
}
if ($dateF !== '') {
    // o günün başı / sonu aralığı
    $conditions[] = "DATE(l.created_at) = ?";
    $params[] = $dateF;
}

if (!empty($conditions)) {
    $sql .= " WHERE " . implode(" AND ", $conditions);
}

$sql .= " ORDER BY l.created_at DESC LIMIT 500"; // son 500 log

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$logs = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Kullanıcı select'i için liste
$usersStmt = $pdo->query("SELECT id, name FROM users ORDER BY name");
$usersAll  = $usersStmt->fetchAll(PDO::FETCH_ASSOC);

$roleLabels = [
    1 => 'Admin',
    2 => 'Çağrı Merkezi',
    3 => 'Teknisyen'
];

// Action label'ları
$actionLabels = [
    'create'        => 'Yeni İş',
    'update'        => 'Güncelleme',
    'status_change' => 'Durum Değişikliği',
    'file_upload'   => 'Dosya Yükleme'
];
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>İş Log Kayıtları</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="style.css">
    <style>
        .log-filter-form {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: flex-end;
            margin-bottom: 15px;
        }
        .log-filter-form label {
            display: flex;
            flex-direction: column;
            font-size: 14px;
        }
        .log-filter-form input,
        .log-filter-form select {
            padding: 5px 8px;
            border-radius: 4px;
            border: 1px solid #ccc;
            min-width: 120px;
        }
        .badge {
            display: inline-block;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 12px;
        }
        .badge-role-admin { background:#222; color:#fff; }
        .badge-role-call { background:#007bff; color:#fff; }
        .badge-role-tech  { background:#28a745; color:#fff; }

        .badge-act-create  { background:#17a2b8; color:#fff; }
        .badge-act-update  { background:#ffc107; color:#333; }
        .badge-act-status  { background:#6f42c1; color:#fff; }
        .badge-act-file    { background:#20c997; color:#fff; }

        .log-desc {
            font-size: 12px;
            color: #555;
        }
        .log-time {
            font-size: 12px;
            color: #666;
            white-space: nowrap;
        }

        @media (max-width: 768px) {
            .table-wrapper table,
            .table-wrapper thead,
            .table-wrapper tbody,
            .table-wrapper th,
            .table-wrapper td,
            .table-wrapper tr {
                display: block;
            }
            .table-wrapper tr {
                border: 1px solid #ddd;
                margin-bottom: 8px;
                padding: 6px;
                border-radius: 6px;
            }
            .table-wrapper td {
                border: none;
                padding: 3px 0;
            }
            .table-wrapper th {
                display: none;
            }
        }
    </style>
</head>
<body>

<div class="container">

    <div class="top-bar">
        <div><strong>Hoş geldin, <?php echo htmlspecialchars($user['name']); ?></strong></div>
        <div>
            <a href="jobs.php" class="btn">İşler</a>
            <?php if ($user['role'] == 1): ?>
                <a href="technician_create.php" class="btn">Teknisyen Ekle</a>
                <a href="user_callcenter_add.php" class="btn">Çağrı Merkezi Ekle</a>
                <a href="users.php" class="btn">Kullanıcılar</a>
            <?php endif; ?>
            <a href="log_helper.php" class="btn">Loglar</a>
            <a href="logout.php" class="btn">Çıkış</a>
        </div>
    </div>

    <div class="card">
        <h1>İş Log Kayıtları</h1>

        <!-- Filtre formu -->
        <form method="get" class="log-filter-form">
            <label>
                İş ID:
                <input type="number" name="job_id"
                       value="<?php echo htmlspecialchars($jobId ?: ''); ?>"
                       placeholder="örn: 15">
            </label>

            <label>
                Kullanıcı:
                <select name="user_id">
                    <option value="0">Tümü</option>
                    <?php foreach ($usersAll as $u): ?>
                        <option value="<?php echo $u['id']; ?>"
                            <?php echo ($userId == $u['id']) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($u['name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </label>

            <label>
                İşlem:
                <select name="action">
                    <option value="">Tümü</option>
                    <?php foreach ($actionLabels as $ak => $al): ?>
                        <option value="<?php echo htmlspecialchars($ak); ?>"
                            <?php echo ($actionF === $ak ? 'selected' : ''); ?>>
                            <?php echo htmlspecialchars($al); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </label>

            <label>
                Tarih:
                <input type="date" name="date"
                       value="<?php echo htmlspecialchars($dateF); ?>">
            </label>

            <button type="submit" class="btn">Filtrele</button>
            <?php if ($jobId || $userId || $actionF || $dateF): ?>
                <a href="job_logs.php" class="btn">Temizle</a>
            <?php endif; ?>
        </form>

        <div class="table-wrapper">
            <table>
                <thead>
                <tr>
                    <th>#</th>
                    <th>İş</th>
                    <th>Kullanıcı</th>
                    <th>İşlem</th>
                    <th>Durum</th>
                    <th>Açıklama</th>
                    <th>Tarih / Saat</th>
                </tr>
                </thead>
                <tbody>
                <?php if (empty($logs)): ?>
                    <tr>
                        <td colspan="7" style="text-align:center;">Log kaydı bulunamadı.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($logs as $row): ?>
                        <?php
                        $act = $row['action'];
                        // role badge
                        $role = (int)($row['user_role'] ?? 0);
                        $roleClass = '';
                        if     ($role === 1) $roleClass = 'badge-role-admin';
                        elseif ($role === 2) $roleClass = 'badge-role-call';
                        elseif ($role === 3) $roleClass = 'badge-role-tech';

                        // action badge
                        $actClass = '';
                        if     ($act === 'create')        $actClass = 'badge-act-create';
                        elseif ($act === 'update')        $actClass = 'badge-act-update';
                        elseif ($act === 'status_change') $actClass = 'badge-act-status';
                        elseif ($act === 'file_upload')   $actClass = 'badge-act-file';

                        $actText = $actionLabels[$act] ?? $act;
                        ?>
                        <tr>
                            <td><?php echo (int)$row['id']; ?></td>
                            <td>
                                <?php if ($row['job_id']): ?>
                                    <a href="job_edit.php?id=<?php echo (int)$row['job_id']; ?>" class="btn btn-small">
                                        #<?php echo (int)$row['job_id']; ?>
                                    </a><br>
                                <?php endif; ?>
                                <?php if (!empty($row['job_title'])): ?>
                                    <?php echo htmlspecialchars($row['job_title']); ?><br>
                                <?php endif; ?>
                                <?php if (!empty($row['customer_name'])): ?>
                                    <small><?php echo htmlspecialchars($row['customer_name']); ?></small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php echo htmlspecialchars($row['user_name'] ?? '-'); ?><br>
                                <?php if ($roleClass): ?>
                                    <span class="badge <?php echo $roleClass; ?>">
                                        <?php echo htmlspecialchars($roleLabels[$role] ?? ''); ?>
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="badge <?php echo $actClass; ?>">
                                    <?php echo htmlspecialchars($actText); ?>
                                </span>
                            </td>
                            <td>
                                <?php if ($row['old_status'] || $row['new_status']): ?>
                                    <small>
                                        <?php echo htmlspecialchars($row['old_status'] ?? '-'); ?>
                                        →
                                        <?php echo htmlspecialchars($row['new_status'] ?? '-'); ?>
                                    </small>
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if (!empty($row['description'])): ?>
                                    <div class="log-desc">
                                        <?php echo nl2br(htmlspecialchars($row['description'])); ?>
                                    </div>
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </td>
                            <td class="log-time">
                                <?php echo htmlspecialchars($row['created_at']); ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

    </div>

</div>

</body>
</html>
