<?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();
$user = null;
$projects = [];
$ozluk_dosyalari = [];
$message = $_GET['message'] ?? '';
$message_type = $_GET['status'] ?? '';
$user_id = $_GET['id'] ?? 0;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'upload_ozluk_dosyasi') {
        $personnel_id = $_POST['personnel_id'] ?? 0;
        $document_category = $_POST['document_category'] ?? 'Diğer Belgeler';
        if (isset($_FILES['ozluk_dosyasi']) && $_FILES['ozluk_dosyasi']['error'] === UPLOAD_ERR_OK) {
            $file_name = $_FILES['ozluk_dosyasi']['name'];
            $file_tmp_name = $_FILES['ozluk_dosyasi']['tmp_name'];
            $upload_dir = __DIR__ . '/uploads/ozluk_dosyalari/';
            
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }

            $unique_file_name = uniqid() . '-' . basename($file_name);
            $destination = $upload_dir . $unique_file_name;

            if (move_uploaded_file($file_tmp_name, $destination)) {
                try {
                    $stmt = $conn->prepare("INSERT INTO personnel_ozluk_dosyalari (personnel_id, document_name, file_path, category) VALUES (?, ?, ?, ?)");
                    $stmt->execute([$personnel_id, $file_name, $destination, $document_category]);
                    $message = 'Dosya başarıyla yüklendi!';
                    $message_type = 'success';
                } catch (PDOException $e) {
                    $message = 'Veritabanı hatası: ' . $e->getMessage();
                    $message_type = 'error';
                }
            } else {
                $message = 'Dosya yüklenirken bir hata oluştu.';
                $message_type = 'error';
            }
        } else {
            $message = 'Lütfen geçerli bir dosya seçin.';
            $message_type = 'error';
        }
        header("Location: view_user.php?id=$user_id&status=$message_type&message=" . urlencode($message));
        exit;
    }
}

if ($user_id > 0) {
    try {
        $stmt_user = $conn->prepare("SELECT id, name, title, email, role, created_at, phone, address, company_info, tc_no, country, city FROM users WHERE id = ?");
        $stmt_user->execute([$user_id]);
        $user = $stmt_user->fetch(PDO::FETCH_ASSOC);

        $stmt_projects = $conn->prepare("SELECT id, project_name FROM projects WHERE assigned_to_user_id = ?");
        $stmt_projects->execute([$user_id]);
        $projects = $stmt_projects->fetchAll(PDO::FETCH_ASSOC);

        $stmt_files = $conn->prepare("SELECT * FROM personnel_ozluk_dosyalari WHERE personnel_id = ? ORDER BY upload_date DESC");
        $stmt_files->execute([$user_id]);
        $ozluk_dosyalari = $stmt_files->fetchAll(PDO::FETCH_ASSOC);
        
    } catch (PDOException $e) {
        die("Hata: " . $e->getMessage());
    }
}
if (!$user) {
    die("Kullanıcı bulunamadı.");
}

$categories = [
    'Kimlik ve Temel Belgeler', 'İşe Alım Belgeleri', 'Ücret ve Mali Belgeler', 'Sağlık ve Eğitim Belgeleri', 'Diğer Belgeler'
];
$categorized_files = [];
foreach ($categories as $cat) {
    $categorized_files[$cat] = array_filter($ozluk_dosyalari, function($file) use ($cat) {
        return $file['category'] === $cat;
    });
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Kullanıcı Detayı: <?php echo htmlspecialchars($user['name']); ?></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="user-profile-container">
        <div class="profile-main">
            <div class="profile-card">
                <h3>Kişisel Bilgiler</h3>
                <div class="profile-info-grid">
                    <div><strong>Adı:</strong> <?php echo htmlspecialchars($user['name']); ?></div>
                    <div><strong>Ünvanı:</strong> <?php echo htmlspecialchars($user['title'] ?? '-'); ?></div>
                    <div><strong>E-posta:</strong> <?php echo htmlspecialchars($user['email']); ?></div>
                    <div><strong>Telefon:</strong> <?php echo htmlspecialchars($user['phone'] ?? '-'); ?></div>
                    <div><strong>TC No:</strong> <?php echo htmlspecialchars($user['tc_no'] ?? '-'); ?></div>
                </div>
            </div>

            <div class="profile-card">
                <h3>Adres Bilgileri</h3>
                <div class="profile-info-grid">
                    <div><strong>Ülke:</strong> <?php echo htmlspecialchars($user['country'] ?? '-'); ?></div>
                    <div><strong>Şehir:</strong> <?php echo htmlspecialchars($user['city'] ?? '-'); ?></div>
                    <div class="full-width"><strong>Adres:</strong> <?php echo htmlspecialchars($user['address'] ?? '-'); ?></div>
                </div>
            </div>

            <div class="profile-card">
                <h3>Firma Bilgileri</h3>
                <div class="profile-info-grid">
                    <div class="full-width"><strong>Firma Adı:</strong> <?php echo htmlspecialchars($user['company_info'] ?? '-'); ?></div>
                </div>
            </div>

            <div class="profile-card">
                <h3>Özlük Dosyaları</h3>
                <div class="ozluk-upload-form">
                    <form action="view_user.php?id=<?php echo $user_id; ?>" method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="action" value="upload_ozluk_dosyasi">
                        <input type="hidden" name="personnel_id" value="<?php echo $user_id; ?>">
                        <div class="form-grid">
                            <div class="form-group">
                                <label for="ozluk_dosyasi">Dosya Seç:</label>
                                <input type="file" id="ozluk_dosyasi" name="ozluk_dosyasi" required>
                            </div>
                            <div class="form-group">
                                <label for="document_category">Kategori Seç:</label>
                                <select id="document_category" name="document_category" required>
                                    <option value="Kimlik ve Temel Belgeler">Kimlik ve Temel Belgeler</option>
                                    <option value="İşe Alım Belgeleri">İşe Alım Belgeleri</option>
                                    <option value="Ücret ve Mali Belgeler">Ücret ve Mali Belgeler</option>
                                    <option value="Sağlık ve Eğitim Belgeleri">Sağlık ve Eğitim Belgeleri</option>
                                    <option value="Diğer Belgeler">Diğer Belgeler</option>
                                </select>
                            </div>
                        </div>
                        <button type="submit">Dosya Yükle</button>
                    </form>
                </div>
                
                <hr>
                
                <h4>Yüklü Dosyaların Listesi</h4>
                <?php if ($message): ?>
                    <p class="message" style="color: <?php echo $message_type === 'success' ? 'green' : 'red'; ?>;">
                        <?php echo htmlspecialchars($message); ?>
                    </p>
                <?php endif; ?>
                
                <?php if (empty($ozluk_dosyalari)): ?>
                    <p>Bu personele ait yüklü bir dosya bulunmamaktadır.</p>
                <?php else: ?>
                    <?php foreach ($categories as $cat): ?>
                        <?php if (!empty($categorized_files[$cat])): ?>
                            <h5><?php echo htmlspecialchars($cat); ?></h5>
                            <div class="file-list">
                                <?php foreach ($categorized_files[$cat] as $dosya): ?>
                                    <div class="file-item">
                                        <span><?php echo htmlspecialchars($dosya['document_name']); ?></span>
                                        <a href="download.php?file_id=<?php echo $dosya['id']; ?>&table=personnel_ozluk_dosyalari" class="btn btn-primary btn-sm">İndir</a>
                                        <a href="delete.php?table=personnel_ozluk_dosyalari&id=<?php echo $dosya['id']; ?>&redirect=view_user.php?id=<?php echo $user_id; ?>" class="delete-btn btn-sm" onclick="return confirm('Bu dosyayı silmek istediğinizden emin misiniz?');">Sil</a>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <div class="profile-sidebar">
            <div class="sidebar-card">
                <h3>Kayıt Bilgileri</h3>
                <p><strong>Yetki:</strong> <?php echo htmlspecialchars(ucfirst($user['role'])); ?></p>
                <p><strong>Eklenme Tarihi:</strong> <?php echo htmlspecialchars($user['created_at']); ?></p>
            </div>
            
            <div class="sidebar-card">
                <h3>Atanan Projeler</h3>
                <?php if (!empty($projects)): ?>
                    <ul>
                        <?php foreach ($projects as $project): ?>
                            <li><a href="view_project.php?id=<?php echo $project['id']; ?>"><?php echo htmlspecialchars($project['project_name']); ?></a></li>
                        <?php endforeach; ?>
                    </ul>
                <?php else: ?>
                    <p>Atanmış proje yok.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</main>
</body>
</html>