<?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;

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_leave') {
    $personnel_id = $_POST['personnel_id'] ?? 0;
    $leave_type = $_POST['leave_type'] ?? '';
    $start_date = $_POST['start_date'] ?? '';
    $end_date = $_POST['end_date'] ?? '';
    $notes = $_POST['notes'] ?? '';
    
    try {
        $stmt = $conn->prepare("INSERT INTO personnel_leaves (personnel_id, leave_type, start_date, end_date, notes) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$personnel_id, $leave_type, $start_date, $end_date, $notes]);
        $message = 'Yeni izin talebi başarıyla eklendi!';
        $message_type = 'success';
        header("Location: izinler.php?status=success&message=" . urlencode($message));
        exit;
    } catch (PDOException $e) {
        $message = 'Hata: İzin talebi eklenirken bir sorun oluştu. ' . $e->getMessage();
        $message_type = 'error';
        header("Location: izinler.php?status=error&message=" . urlencode($message));
        exit;
    }
}

try {
    $stmt_personnel = $conn->prepare("SELECT id, full_name FROM personnel ORDER BY full_name ASC");
    $stmt_personnel->execute();
    $personnel = $stmt_personnel->fetchAll(PDO::FETCH_ASSOC);

    $stmt_leaves = $conn->prepare("SELECT pl.*, p.full_name FROM personnel_leaves pl JOIN personnel p ON pl.personnel_id = p.id ORDER BY pl.created_at DESC");
    $stmt_leaves->execute();
    $leaves = $stmt_leaves->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    die("Hata: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Hati App - İzinler</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>İzinler</h2>
    <a href="personel.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; ?>
<div class="detail-box">
    <h3 class="detail-box-title">Yeni İzin Talebi Oluştur</h3>
    <form action="izinler.php" method="POST">
        <input type="hidden" name="action" value="add_leave">
        <div class="form-grid">
            <div class="form-group">
                <label for="personnel_id">Personel Seç:</label>
                <select id="personnel_id" name="personnel_id" required>
                    <option value="">Seçiniz</option>
                    <?php foreach ($personnel as $p): ?>
                        <option value="<?php echo $p['id']; ?>"><?php echo htmlspecialchars($p['full_name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label for="leave_type">İzin Türü:</label>
                <input type="text" id="leave_type" name="leave_type" 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>
        <div class="form-group full-width">
            <label for="notes">Notlar:</label>
            <textarea id="notes" name="notes" rows="3"></textarea>
        </div>
        <div class="form-actions">
            <button type="submit">Talep Oluştur</button>
        </div>
    </form>
</div>
<hr>
<h3>Mevcut İzin Talepleri</h3>
<?php if (empty($leaves)): ?>
    <p>Henüz izin talebi bulunmamaktadır.</p>
<?php else: ?>
    <table>
        <thead>
            <tr>
                <th>Personel</th>
                <th>İzin Türü</th>
                <th>Başlangıç</th>
                <th>Bitiş</th>
                <th>Durum</th>
                <th>İşlemler</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($leaves as $leave): ?>
            <tr>
                <td><?php echo htmlspecialchars($leave['full_name']); ?></td>
                <td><?php echo htmlspecialchars($leave['leave_type']); ?></td>
                <td><?php echo htmlspecialchars($leave['start_date']); ?></td>
                <td><?php echo htmlspecialchars($leave['end_date']); ?></td>
                <td>
                    <?php 
                    $statusInfo = getStatusInfo($leave['status']); 
                    ?>
                    <span class="status <?php echo $statusInfo['class']; ?>"><?php echo $statusInfo['label']; ?></span>
                </td>
                <td>
                    <a href="delete.php?table=personnel_leaves&id=<?php echo $leave['id']; ?>&redirect=izinler.php" onclick="return confirm('Bu kaydı silmek istediğinizden emin misiniz?');">Sil</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
<?php endif; ?>
</body>
</html>