<?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();
$message = $_GET['message'] ?? '';
$message_type = $_GET['status'] ?? '';
$vehicles = [];
try {
    $stmt = $conn->prepare("SELECT * FROM vehicles ORDER BY plate_number ASC");
    $stmt->execute();
    $vehicles = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    echo "Hata: " . $e->getMessage();
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Hati App - Araç Yönetimi</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>Araç Yönetimi</h2>
    <a href="create_arac.php">Yeni Araç Ekle</a>
</div>
<?php if ($message): ?>
    <p style="color: <?php echo $message_type === 'success' ? 'green' : 'red'; ?>;">
        <?php echo htmlspecialchars($message); ?>
    </p>
<?php endif; ?>
<h3>Mevcut Araçlar</h3>
<?php if (empty($vehicles)): ?>
    <p>Henüz kayıtlı bir araç bulunmamaktadır.</p>
<?php else: ?>
    <table>
        <thead>
            <tr>
                <th>Plaka</th>
                <th>Marka/Model</th>
                <th>Yıl</th>
                <th>Güncel KM</th>
                <th>İşlemler</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($vehicles as $vehicle): ?>
            <tr>
                <td><?php echo htmlspecialchars($vehicle['plate_number']); ?></td>
                <td><?php echo htmlspecialchars($vehicle['brand'] ?? '-') . ' ' . htmlspecialchars($vehicle['model'] ?? '-'); ?></td>
                <td><?php echo htmlspecialchars($vehicle['year'] ?? '-'); ?></td>
                <td><?php echo number_format($vehicle['current_km']); ?></td>
                <td>
                    <a href="view_arac.php?id=<?php echo $vehicle['id']; ?>">Gör</a> |
                    <a href="delete.php?table=vehicles&id=<?php echo $vehicle['id']; ?>&redirect=araclar.php" onclick="return confirm('Bu aracı silmek istediğinizden emin misiniz?');">Sil</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
<?php endif; ?>
</main>
</body>
</html>