<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}
require_once __DIR__ . '/../src/Core/Database.php';
use HatiApp\Core\Database;
$message = '';
$message_type = '';
$db = new Database();
$conn = $db->getConnection();
$users = [];
try {
    $stmt = $conn->prepare("SELECT id, name FROM users WHERE role IN ('employee', 'admin') ORDER BY name ASC");
    $stmt->execute();
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    echo "Hata: " . $e->getMessage();
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $job_title = $_POST['job_title'] ?? '';
    $description = $_POST['description'] ?? '';
    $assigned_to_user_id = $_POST['assigned_to_user_id'] ?? null;
    $created_by_user_id = $_SESSION['user_id'];
    try {
        $stmt = $conn->prepare("INSERT INTO missing_jobs (job_title, description, created_by_user_id, assigned_to_user_id) VALUES (?, ?, ?, ?)");
        $stmt->execute([$job_title, $description, $created_by_user_id, $assigned_to_user_id]);
        $message = 'Eksik iş kaydı başarıyla oluşturuldu!';
        $message_type = 'success';
    } catch (PDOException $e) {
        $message = 'Hata: Kayıt oluşturulurken bir sorun oluştu. ' . $e->getMessage();
        $message_type = 'error';
    }
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Yeni Eksik İş Ekle</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
<?php require_once __DIR__ . '/../src/Includes/header.php'; ?>
    <h2>Yeni Eksik İş Kaydı Oluştur</h2>
    <?php if ($message): ?>
        <p style="color: <?php echo $message_type === 'success' ? 'green' : 'red'; ?>;">
            <?php echo htmlspecialchars($message); ?>
        </p>
    <?php endif; ?>
    <form action="create_missing_job.php" method="POST">
        <div>
            <label for="job_title">İşin Başlığı:</label>
            <input type="text" id="job_title" name="job_title" required>
        </div>
        <div>
            <label for="description">Açıklama:</label>
            <textarea id="description" name="description" rows="5"></textarea>
        </div>
        <div>
            <label for="assigned_to_user_id">Atanan Kişi:</label>
            <select id="assigned_to_user_id" name="assigned_to_user_id">
                <option value="">Atama Yapma</option>
                <?php foreach ($users as $user): ?>
                    <option value="<?php echo $user['id']; ?>"><?php echo htmlspecialchars($user['name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <button type="submit">İşi Kaydet</button>
        </div>
    </form>
</main>
</body>
</html>