<?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'] ?? '';
$vehicle = null;
$insurance_records = [];
$maintenance_records = [];
$inspection_records = [];
$hgs_records = [];
$penalty_records = [];

$vehicle_id = $_GET['id'] ?? ($_POST['id'] ?? 0);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    // Ceza Ekleme İşlemi
    if ($action === 'add_penalty') {
        $penalty_date = $_POST['penalty_date'] ?? date('Y-m-d');
        $penalty_amount = $_POST['penalty_amount'] ?? 0;
        $description = $_POST['description'] ?? '';
        try {
            $stmt = $conn->prepare("INSERT INTO vehicle_penalties (vehicle_id, penalty_date, penalty_amount, description) VALUES (?, ?, ?, ?)");
            $stmt->execute([$vehicle_id, $penalty_date, $penalty_amount, $description]);
            $message = 'Yeni ceza kaydı başarıyla eklendi.';
            $message_type = 'success';
        } catch (PDOException $e) {
            $message = 'Ceza kaydı eklenirken bir hata oluştu: ' . $e->getMessage();
            $message_type = 'error';
        }
    } 
    // KM Güncelleme İşlemi
    elseif ($action === 'update_km') {
        $new_km = $_POST['current_km'] ?? $vehicle['current_km'];
        try {
            $stmt_update = $conn->prepare("UPDATE vehicles SET current_km = ? WHERE id = ?");
            $stmt_update->execute([$new_km, $vehicle_id]);
            $message = 'Kilometre bilgisi başarıyla güncellendi.';
            $message_type = 'success';
        } catch (PDOException $e) {
            $message = 'Güncelleme sırasında bir hata oluştu: ' . $e->getMessage();
            $message_type = 'error';
        }
    } 
    // Bakım Ekleme İşlemi
    elseif ($action === 'add_maintenance') {
        $maintenance_type = $_POST['maintenance_type'] ?? '';
        $maintenance_date = $_POST['maintenance_date'] ?? date('Y-m-d');
        $cost = $_POST['cost'] ?? 0;
        $description = $_POST['description'] ?? '';
        try {
            $stmt = $conn->prepare("INSERT INTO vehicle_maintenance (vehicle_id, maintenance_type, maintenance_date, description, cost) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$vehicle_id, $maintenance_type, $maintenance_date, $description, $cost]);
            $message = 'Bakım kaydı başarıyla eklendi.';
            $message_type = 'success';
        } catch (PDOException $e) {
            $message = 'Bakım kaydı eklenirken bir hata oluştu: ' . $e->getMessage();
            $message_type = 'error';
        }
    } 
    // Sigorta Ekleme İşlemi
    elseif ($action === 'add_insurance') {
        $policy_number = $_POST['policy_number'] ?? '';
        $company_name = $_POST['company_name'] ?? '';
        $start_date = $_POST['start_date'] ?? date('Y-m-d');
        $end_date = $_POST['end_date'] ?? date('Y-m-d');
        $cost = $_POST['cost'] ?? 0;
        try {
            $stmt = $conn->prepare("INSERT INTO vehicle_insurance (vehicle_id, policy_number, company_name, start_date, end_date, cost) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$vehicle_id, $policy_number, $company_name, $start_date, $end_date, $cost]);
            $message = 'Sigorta kaydı başarıyla eklendi.';
            $message_type = 'success';
        } catch (PDOException $e) {
            $message = 'Sigorta kaydı eklenirken bir hata oluştu: ' . $e->getMessage();
            $message_type = 'error';
        }
    }
    // Muayene Ekleme İşlemi
    elseif ($action === 'add_inspection') {
        $inspection_date = $_POST['inspection_date'] ?? date('Y-m-d');
        $next_inspection_date = $_POST['next_inspection_date'] ?? date('Y-m-d');
        $notes = $_POST['notes'] ?? '';
        try {
            $stmt = $conn->prepare("INSERT INTO vehicle_inspection (vehicle_id, inspection_date, next_inspection_date, notes) VALUES (?, ?, ?, ?)");
            $stmt->execute([$vehicle_id, $inspection_date, $next_inspection_date, $notes]);
            $message = 'Muayene kaydı başarıyla eklendi.';
            $message_type = 'success';
        } catch (PDOException $e) {
            $message = 'Muayene kaydı eklenirken bir hata oluştu: ' . $e->getMessage();
            $message_type = 'error';
        }
    }
    // HGS Ekleme İşlemi
    elseif ($action === 'add_hgs') {
        $hgs_no = $_POST['hgs_no'] ?? '';
        $balance = $_POST['balance'] ?? 0;
        try {
            $stmt = $conn->prepare("INSERT INTO vehicle_hgs (vehicle_id, hgs_no, balance) VALUES (?, ?, ?)");
            $stmt->execute([$vehicle_id, $hgs_no, $balance]);
            $message = 'HGS kaydı başarıyla eklendi.';
            $message_type = 'success';
        } catch (PDOException $e) {
            $message = 'HGS kaydı eklenirken bir hata oluştu: ' . $e->getMessage();
            $message_type = 'error';
        }
    }
    // Yönlendirme
    header("Location: view_arac.php?id=$vehicle_id&status=$message_type&message=" . urlencode($message));
    exit;
}


if ($vehicle_id > 0) {
    try {
        $stmt = $conn->prepare("SELECT * FROM vehicles WHERE id = ?");
        $stmt->execute([$vehicle_id]);
        $vehicle = $stmt->fetch(PDO::FETCH_ASSOC);

        $stmt_ins = $conn->prepare("SELECT * FROM vehicle_insurance WHERE vehicle_id = ? ORDER BY end_date DESC");
        $stmt_ins->execute([$vehicle_id]);
        $insurance_records = $stmt_ins->fetchAll(PDO::FETCH_ASSOC);

        $stmt_maint = $conn->prepare("SELECT * FROM vehicle_maintenance WHERE vehicle_id = ? ORDER BY maintenance_date DESC");
        $stmt_maint->execute([$vehicle_id]);
        $maintenance_records = $stmt_maint->fetchAll(PDO::FETCH_ASSOC);

        $stmt_insp = $conn->prepare("SELECT * FROM vehicle_inspection WHERE vehicle_id = ? ORDER BY inspection_date DESC");
        $stmt_insp->execute([$vehicle_id]);
        $inspection_records = $stmt_insp->fetchAll(PDO::FETCH_ASSOC);

        $stmt_hgs = $conn->prepare("SELECT * FROM vehicle_hgs WHERE vehicle_id = ? ORDER BY created_at DESC");
        $stmt_hgs->execute([$vehicle_id]);
        $hgs_records = $stmt_hgs->fetchAll(PDO::FETCH_ASSOC);
        
        $stmt_penalty = $conn->prepare("SELECT * FROM vehicle_penalties WHERE vehicle_id = ? ORDER BY penalty_date DESC");
        $stmt_penalty->execute([$vehicle_id]);
        $penalty_records = $stmt_penalty->fetchAll(PDO::FETCH_ASSOC);

    } catch (PDOException $e) {
        $message = 'Hata: ' . $e->getMessage();
        $message_type = 'error';
    }
}
if (!$vehicle) {
    echo "Hata: Araç kaydı bulunamadı.";
    exit;
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Araç Detayı: <?php echo htmlspecialchars($vehicle['plate_number'] ?? ''); ?></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ç Detayı: <?php echo htmlspecialchars($vehicle['plate_number'] ?? ''); ?></h2>
    <a href="araclar.php" class="secondary-btn">Geri Dön</a>
</div>
<?php if ($message): ?>
    <p class="message" style="color: <?php echo $message_type === 'success' ? 'green' : 'red'; ?>;">
        <?php echo htmlspecialchars($message); ?>
    </p>
<?php endif; ?>
<?php if ($vehicle): ?>
    
    <div class="detail-box-grid">
        <div class="detail-box">
            <h3 class="detail-box-title">Araç Bilgileri</h3>
            <div class="detail-grid">
                <div><strong>Plaka:</strong> <?php echo htmlspecialchars($vehicle['plate_number']); ?></div>
                <div><strong>Marka:</strong> <?php echo htmlspecialchars($vehicle['brand'] ?? '-'); ?></div>
                <div><strong>Model:</strong> <?php echo htmlspecialchars($vehicle['model'] ?? '-'); ?></div>
                <div><strong>Yıl:</strong> <?php echo htmlspecialchars($vehicle['year'] ?? '-'); ?></div>
                <div class="full-width"><strong>Güncel KM:</strong> <?php echo number_format($vehicle['current_km']); ?> km</div>
                <?php if ($_SESSION['user_role'] === 'admin'): ?>
                <div class="full-width">
                    <form action="view_arac.php?id=<?php echo $vehicle['id']; ?>" method="POST" class="inline-form" style="display: flex; gap: 10px; align-items: center;">
                        <input type="hidden" name="action" value="update_km">
                        <label for="current_km_input" style="margin-bottom: 0; font-weight: bold;">KM Güncelle:</label>
                        <input type="number" id="current_km_input" name="current_km" step="1" min="0" value="<?php echo htmlspecialchars($vehicle['current_km']); ?>" required style="flex-grow: 1;">
                        <button type="submit" class="btn btn-primary" style="width: auto; padding: 10px;">Güncelle</button>
                    </form>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="detail-box">
            <h3 class="detail-box-title">Cezalar</h3>
            <h4>Yeni Ceza Kaydı</h4>
            <form action="view_arac.php?id=<?php echo $vehicle['id']; ?>" method="POST">
                <input type="hidden" name="action" value="add_penalty">
                <div class="form-grid">
                    <div class="form-group">
                        <label for="penalty_date">Ceza Tarihi:</label>
                        <input type="date" id="penalty_date" name="penalty_date" value="<?php echo date('Y-m-d'); ?>" required>
                    </div>
                    <div class="form-group">
                        <label for="penalty_amount">Ceza Tutarı (TL):</label>
                        <input type="number" id="penalty_amount" name="penalty_amount" step="0.01" min="0" required>
                    </div>
                    <div class="form-group full-width">
                        <label for="description">Açıklama / Konu:</label>
                        <textarea id="description" name="description" rows="2"></textarea>
                    </div>
                </div>
                <button type="submit">Ceza Kaydet</button>
            </form>
            <hr>
            <h4>Kayıtlı Cezalar</h4>
            <?php if (empty($penalty_records)): ?>
                <p>Bu araca ait kayıtlı ceza bulunmamaktadır.</p>
            <?php else: ?>
                <table>
                    <thead>
                        <tr>
                            <th>Tarih</th>
                            <th>Tutar</th>
                            <th>Durum</th>
                            <th>Açıklama</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($penalty_records as $rec): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($rec['penalty_date']); ?></td>
                                <td><?php echo number_format($rec['penalty_amount'], 2, ',', '.'); ?> TL</td>
                                <td>
                                    <span class="status <?php echo $rec['is_paid'] ? 'status-success' : 'status-warning'; ?>"><?php echo $rec['is_paid'] ? 'Ödendi' : 'Ödenmedi'; ?></span>
                                </td>
                                <td><?php echo htmlspecialchars($rec['description'] ?? '-'); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>

    <div class="detail-box-grid">
        <div class="detail-box">
            <h3 class="detail-box-title">Sigorta Takibi</h3>
            <div><strong>Son Poliçe Bitişi:</strong> <?php echo htmlspecialchars($insurance_records[0]['end_date'] ?? '-'); ?></div>
            <hr>
            <h4>Yeni Sigorta Kaydı</h4>
            <form action="view_arac.php?id=<?php echo $vehicle['id']; ?>" method="POST">
                <input type="hidden" name="action" value="add_insurance">
                <div class="form-grid">
                    <div class="form-group">
                        <label for="policy_number">Poliçe No:</label>
                        <input type="text" id="policy_number" name="policy_number" required>
                    </div>
                    <div class="form-group">
                        <label for="company_name">Sigorta Şirketi:</label>
                        <input type="text" id="company_name" name="company_name" required>
                    </div>
                    <div class="form-group">
                        <label for="start_date">Başlangıç Tarihi:</label>
                        <input type="date" id="start_date" name="start_date" required>
                    </div>
                    <div class="form-group">
                        <label for="end_date">Bitiş Tarihi:</label>
                        <input type="date" id="end_date" name="end_date" required>
                    </div>
                    <div class="form-group">
                        <label for="cost">Maliyet (TL):</label>
                        <input type="number" id="cost" name="cost" step="0.01" required>
                    </div>
                </div>
                <button type="submit">Kaydet</button>
            </form>
            <hr>
            <h4>Geçmiş Sigorta Kayıtları</h4>
            </div>

        <div class="detail-box">
            <h3 class="detail-box-title">Muayene ve HGS Takibi</h3>
            <div><strong>Son Muayene Bitişi:</strong> <?php echo htmlspecialchars($inspection_records[0]['next_inspection_date'] ?? '-'); ?></div>
            <hr>
            <h4>Yeni Muayene Kaydı</h4>
            <form action="view_arac.php?id=<?php echo $vehicle['id']; ?>" method="POST">
                <input type="hidden" name="action" value="add_inspection">
                <div class="form-grid">
                    <div class="form-group">
                        <label for="inspection_date">Muayene Tarihi:</label>
                        <input type="date" id="inspection_date" name="inspection_date" required>
                    </div>
                    <div class="form-group">
                        <label for="next_inspection_date">Sonraki Muayene Tarihi:</label>
                        <input type="date" id="next_inspection_date" name="next_inspection_date" required>
                    </div>
                    <div class="form-group full-width">
                        <label for="notes">Notlar:</label>
                        <textarea id="notes" name="notes" rows="1"></textarea>
                    </div>
                </div>
                <button type="submit">Muayene Kaydet</button>
            </form>
            <hr>
            <h4>HGS/OGS Bilgisi</h4>
            <form action="view_arac.php?id=<?php echo $vehicle['id']; ?>" method="POST">
                <input type="hidden" name="action" value="add_hgs">
                <div class="form-grid">
                    <div class="form-group">
                        <label for="hgs_no">HGS/OGS No:</label>
                        <input type="text" id="hgs_no" name="hgs_no" value="<?php echo htmlspecialchars($hgs_records[0]['hgs_no'] ?? ''); ?>" required>
                    </div>
                    <div class="form-group">
                        <label for="balance">Bakiye (TL):</label>
                        <input type="number" id="balance" name="balance" step="0.01" value="<?php echo htmlspecialchars($hgs_records[0]['balance'] ?? 0); ?>" required>
                    </div>
                </div>
                <button type="submit">HGS/OGS Güncelle</button>
            </form>
        </div>
    </div>

    <div class="detail-box full-width-box">
        <h3 class="detail-box-title">Bakım Geçmişi</h3>
        <?php if (empty($maintenance_records)): ?>
            <p>Bu araca ait bakım kaydı bulunmamaktadır.</p>
        <?php else: ?>
            <table>
                <thead>
                    <tr>
                        <th>Bakım Türü</th>
                        <th>Tarih</th>
                        <th>Maliyet</th>
                        <th>Açıklama</th>
                        <th>İşlemler</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($maintenance_records as $rec): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($rec['maintenance_type']); ?></td>
                            <td><?php echo htmlspecialchars($rec['maintenance_date']); ?></td>
                            <td><?php echo number_format($rec['cost'], 2, ',', '.'); ?> TL</td>
                            <td><?php echo htmlspecialchars($rec['description']); ?></td>
                            <td><a href="delete.php?table=vehicle_maintenance&id=<?php echo $rec['id']; ?>&redirect=view_arac.php?id=<?php echo $vehicle['id']; ?>" onclick="return confirm('Bu kaydı silmek istediğinizden emin misiniz?');">Sil</a></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
        <hr>
        <h4>Yeni Bakım Kaydı</h4>
        <form action="view_arac.php?id=<?php echo $vehicle['id']; ?>" method="POST">
            <input type="hidden" name="action" value="add_maintenance">
            <div class="form-grid">
                <div class="form-group">
                    <label for="maintenance_type_new">Bakım Türü:</label>
                    <input type="text" id="maintenance_type_new" name="maintenance_type" required>
                </div>
                <div class="form-group">
                    <label for="maintenance_date_new">Bakım Tarihi:</label>
                    <input type="date" id="maintenance_date_new" name="maintenance_date" required>
                </div>
                <div class="form-group">
                    <label for="cost_new">Maliyet (TL):</label>
                    <input type="number" id="cost_new" name="cost" step="0.01" required>
                </div>
            </div>
            <div class="form-group full-width">
                <label for="description_new">Açıklama:</label>
                <textarea id="description_new" name="description" rows="3"></textarea>
            </div>
            <button type="submit">Kaydet</button>
        </form>
    </div>

<?php else: ?>
    <p class="message" style="color: red;">Araç bilgileri yüklenemedi. Lütfen <a href="araclar.php">araçlar sayfasına</a> geri dönün.</p>
<?php endif; ?>
</body>
</html>