<?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();
$documents = [];

// Dosya yükleme işlemleri
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'upload_file') {
    $document_category = $_POST['document_category'] ?? 'Diğer Evraklar';
    if (isset($_FILES['company_document']) && $_FILES['company_document']['error'] === UPLOAD_ERR_OK) {
        $file_name = $_FILES['company_document']['name'];
        $file_tmp_name = $_FILES['company_document']['tmp_name'];
        $upload_dir = __DIR__ . '/uploads/company_documents/';
        
        // Klasör yoksa oluştur
        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 company_documents (document_name, file_path, category, uploaded_by_user_id) VALUES (?, ?, ?, ?)");
                $stmt->execute([$file_name, $destination, $document_category, $_SESSION['user_id']]);
                $message = 'Dosya başarıyla yüklendi!';
                $message_type = 'success';
                header("Location: evraklar.php?status=success&message=" . urlencode($message));
                exit;
            } 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';
    }
}

// Yüklü dosyaları al
try {
    $stmt = $conn->prepare("SELECT cd.*, u.name AS uploaded_by_name FROM company_documents cd JOIN users u ON cd.uploaded_by_user_id = u.id ORDER BY cd.upload_date DESC");
    $stmt->execute();
    $documents = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Hata: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Hati App - Firma Evrakları</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>Firma Evrakları</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">Dosya Yükle</h3>
    <form action="evraklar.php" method="POST" enctype="multipart/form-data">
        <input type="hidden" name="action" value="upload_file">
        <div class="form-grid">
            <div class="form-group">
                <label for="company_document">Dosya Seç:</label>
                <input type="file" id="company_document" name="company_document" required>
            </div>
            <div class="form-group">
                <label for="document_category">Kategori Seç:</label>
                <select id="document_category" name="document_category" required>
                    <option value="Yönetim Kurulu Kararları">Yönetim Kurulu Kararları</option>
                    <option value="Vergi ve SGK Evrakları">Vergi ve SGK Evrakları</option>
                    <option value="Sözleşmeler">Sözleşmeler</option>
                    <option value="Faturalar ve Ödemeler">Faturalar ve Ödemeler</option>
                    <option value="Diğer Evraklar">Diğer Evraklar</option>
                </select>
            </div>
        </div>
        <div class="form-actions">
            <button type="submit">Dosya Yükle</button>
        </div>
    </form>
</div>

<div class="detail-box" style="margin-top: 2rem;">
    <h3 class="detail-box-title">Yüklü Firma Evrakları</h3>
    <?php if (empty($documents)): ?>
        <p>Henüz firma evrağı yüklenmemiştir.</p>
    <?php else: ?>
        <table>
            <thead>
                <tr>
                    <th>Dosya Adı</th>
                    <th>Kategori</th>
                    <th>Yükleyen</th>
                    <th>Yükleme Tarihi</th>
                    <th>İşlemler</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($documents as $doc): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($doc['document_name']); ?></td>
                        <td><?php echo htmlspecialchars($doc['category']); ?></td>
                        <td><?php echo htmlspecialchars($doc['uploaded_by_name']); ?></td>
                        <td><?php echo htmlspecialchars($doc['upload_date']); ?></td>
                        <td>
                            <a href="download.php?file_id=<?php echo $doc['id']; ?>&table=company_documents">İndir</a> |
                            <a href="delete.php?table=company_documents&id=<?php echo $doc['id']; ?>&redirect=evraklar.php" onclick="return confirm('Bu dosyayı silmek istediğinizden emin misiniz?');">Sil</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

</body>
</html>