<?php
session_start();
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: login.php');
    exit;
}
require_once __DIR__ . '/../src/Core/Database.php';
require_once __DIR__ . '/../src/Includes/helpers.php';
use HatiApp\Core\Database;

$db = new Database();
$conn = $db->getConnection();
$jobs = [];
$message = $_GET['message'] ?? '';
$message_type = $_GET['status'] ?? '';

try {
    $stmt = $conn->prepare("SELECT mj.*, u1.name AS created_by, u2.name AS assigned_to FROM missing_jobs mj JOIN users u1 ON mj.created_by_user_id = u1.id LEFT JOIN users u2 ON mj.assigned_to_user_id = u2.id ORDER BY mj.created_at DESC");
    $stmt->execute();
    $jobs = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $message = "Hata: " . $e->getMessage();
    $message_type = 'error';
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Hati App - Eksik İşler</title>
    <link rel="stylesheet" href="css/style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<?php require_once __DIR__ . '/../src/Includes/header.php'; ?>
<div class="header-actions">
    <h2>Eksik İşler</h2>
    <a href="create_missing_job.php">Yeni Eksik İş Ekle</a>
</div>
<?php if ($message): ?>
    <p style="color: <?php echo $message_type === 'success' ? 'green' : 'red'; ?>;"><?php echo htmlspecialchars($message); ?></p>
<?php endif; ?>
<?php if (empty($jobs)): ?>
    <p>Henüz kayıtlı bir eksik iş bulunmamaktadır.</p>
<?php else: ?>
    <table>
        <thead>
            <tr>
                <th>Başlık</th>
                <th>Oluşturan</th>
                <th>Atanan</th>
                <th>Durum</th>
                <th>Tarih</th>
                <th>İşlemler</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($jobs as $job): ?>
            <tr>
                <td><?php echo htmlspecialchars($job['job_title']); ?></td>
                <td><?php echo htmlspecialchars($job['created_by']); ?></td>
                <td><?php echo htmlspecialchars($job['assigned_to'] ?? '-'); ?></td>
                <td>
                    <?php 
                    $statusInfo = getStatusInfo($job['status']); 
                    ?>
                    <span class="status <?php echo $statusInfo['class']; ?>"><?php echo $statusInfo['label']; ?></span>
                </td>
                <td><?php echo htmlspecialchars($job['created_at']); ?></td>
                <td>
                    <a href="delete.php?table=missing_jobs&id=<?php echo $job['id']; ?>&redirect=missing_jobs.php" onclick="return confirm('Bu kaydı silmek istediğinizden emin misiniz?');">Sil</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
<?php endif; ?>
</main>
</body>
</html>