<?php
require_once __DIR__ . '/../../config/secure_bootstrap.php';

// Cek method POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['error'] = 'Method tidak diizinkan';
    header('Location: ../dokumen.php');
    exit;
}

try {
    // Validasi input
    if (empty($_POST['title']) || empty($_POST['category'])) {
        throw new Exception('Judul dan kategori wajib diisi');
    }
    
    // Ambil data form
    $title = trim($_POST['title']);
    $category = trim($_POST['category']);
    $unit_owner = trim($_POST['unit_owner'] ?? '');
    $status = $_POST['status'] ?? 'draft';
    $visibility = $_POST['visibility'] ?? 'internal';
    $notes = trim($_POST['notes'] ?? '');
    $effective_date = !empty($_POST['effective_date']) ? $_POST['effective_date'] : null;
    
    // Generate slug
    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $title)));
    $slug = preg_replace('/-+/', '-', $slug); // Hapus multiple dash
    $slug = trim($slug, '-'); // Hapus dash di awal/akhir
    
    // Cek slug duplicate
    $checkSlug = $pdo->prepare("SELECT COUNT(*) FROM documents WHERE slug = ?");
    $checkSlug->execute([$slug]);
    if ($checkSlug->fetchColumn() > 0) {
        $slug .= '-' . time();
    }
    
    // Validasi file upload
    if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('File dokumen wajib diupload');
    }
    
    $file = $_FILES['file'];
    $file_name_original = $file['name'];
    $file_size = $file['size'];
    $file_tmp = $file['tmp_name'];
    
    // Validasi tipe file
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($finfo, $file_tmp);
    finfo_close($finfo);
    
    $allowed_types = ['application/pdf'];
    if (!in_array($mime_type, $allowed_types)) {
        throw new Exception('File harus berformat PDF');
    }
    
    // Validasi ukuran file (max 10MB)
    $max_size = 10 * 1024 * 1024;
    if ($file_size > $max_size) {
        throw new Exception('Ukuran file maksimal 10MB');
    }
    
    // Generate hash untuk cek duplikasi
    $file_hash = hash_file('sha256', $file_tmp);
    
    // Cek apakah file dengan hash yang sama sudah ada
    $checkHash = $pdo->prepare("SELECT COUNT(*) FROM documents WHERE file_hash = ?");
    $checkHash->execute([$file_hash]);
    if ($checkHash->fetchColumn() > 0) {
        throw new Exception('File dengan konten yang sama sudah pernah diupload');
    }
    
    // Buat direktori upload jika belum ada
    $upload_dir = __DIR__ . '/../../uploads/documents/';
    if (!is_dir($upload_dir)) {
        if (!mkdir($upload_dir, 0755, true)) {
            throw new Exception('Gagal membuat direktori upload');
        }
    }
    
    // Cek permission direktori
    if (!is_writable($upload_dir)) {
        throw new Exception('Direktori upload tidak memiliki permission write');
    }
    
    // Generate nama file unik
    $extension = pathinfo($file_name_original, PATHINFO_EXTENSION);
    $new_filename = date('Ymd_His') . '_' . uniqid() . '.' . strtolower($extension);
    $file_path = 'uploads/documents/' . $new_filename;
    $full_path = __DIR__ . '/../../' . $file_path;
    
    // Upload file
    if (!move_uploaded_file($file_tmp, $full_path)) {
        throw new Exception('Gagal mengupload file. Periksa permission folder.');
    }
    
    // Set permission file
    chmod($full_path, 0644);
    
    // Mulai transaksi
    $pdo->beginTransaction();
    
    try {
        // Simpan ke database
        $stmt = $pdo->prepare("
            INSERT INTO documents 
            (title, slug, category, unit_owner, status, visibility, 
             file_path, file_name_original, mime_type, file_size, file_hash, 
             notes, effective_date, created_by, created_at, updated_at) 
            VALUES 
            (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
        ");
        
        $result = $stmt->execute([
            $title,
            $slug,
            $category,
            $unit_owner,
            $status,
            $visibility,
            $file_path,
            $file_name_original,
            $mime_type,
            $file_size,
            $file_hash,
            $notes,
            $effective_date,
            $_SESSION['user_id']
        ]);
        
        if (!$result) {
            throw new Exception('Gagal menyimpan data ke database');
        }
        
        // Get document ID
        $doc_id = $pdo->lastInsertId();
        
        // Commit transaksi
        $pdo->commit();
        
        // Log aktivitas (setelah commit)
        try {
            $log_stmt = $pdo->prepare("
                INSERT INTO activity_logs (user_id, action, description, created_at) 
                VALUES (?, 'create_document', ?, NOW())
            ");
            $log_stmt->execute([
                $_SESSION['user_id'],
                "Menambahkan dokumen: {$title}"
            ]);
        } catch (Exception $e) {
            // Log error tapi tidak perlu throw, karena dokumen sudah tersimpan
            error_log("Error logging activity: " . $e->getMessage());
        }
        
        $_SESSION['success'] = 'Dokumen berhasil ditambahkan';
        header('Location: ../dokumen.php');
        exit;
        
    } catch (Exception $e) {
        // Rollback transaksi
        $pdo->rollBack();
        
        // Hapus file yang sudah diupload
        if (file_exists($full_path)) {
            unlink($full_path);
        }
        
        throw $e;
    }
    
} catch (Exception $e) {
    $_SESSION['error'] = $e->getMessage();
    
    // Log error
    error_log("Error dokumen_tambah.php: " . $e->getMessage());
    
    header('Location: ../dokumen.php');
    exit;
}