<?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['id']) || empty($_POST['title']) || empty($_POST['category'])) {
        throw new Exception('Data tidak lengkap');
    }
    
    $id = (int)$_POST['id'];
    $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);
    $slug = trim($slug, '-');
    
    // Ambil data dokumen lama
    $stmt = $pdo->prepare("SELECT * FROM documents WHERE id = ?");
    $stmt->execute([$id]);
    $old_doc = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$old_doc) {
        throw new Exception('Dokumen tidak ditemukan');
    }
    
    // Cek slug duplicate (kecuali untuk dokumen ini sendiri)
    $checkSlug = $pdo->prepare("SELECT COUNT(*) FROM documents WHERE slug = ? AND id != ?");
    $checkSlug->execute([$slug, $id]);
    if ($checkSlug->fetchColumn() > 0) {
        $slug .= '-' . time();
    }
    
    // Set default file info dari data lama
    $file_path = $old_doc['file_path'];
    $file_name_original = $old_doc['file_name_original'];
    $mime_type = $old_doc['mime_type'];
    $file_size = $old_doc['file_size'];
    $file_hash = $old_doc['file_hash'];
    
    // Cek apakah ada file baru diupload
    if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
        $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_size = 10 * 1024 * 1024; // 10MB
        if ($file_size > $max_size) {
            throw new Exception('Ukuran file maksimal 10MB');
        }
        
        // Generate hash
        $file_hash = hash_file('sha256', $file_tmp);
        
        // Buat direktori 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
        if (!is_writable($upload_dir)) {
            throw new Exception('Direktori upload tidak memiliki permission write');
        }
        
        // Generate nama file baru
        $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 baru
        if (!move_uploaded_file($file_tmp, $full_path)) {
            throw new Exception('Gagal mengupload file. Periksa permission folder.');
        }
        
        // Set permission
        chmod($full_path, 0644);
        
        // Hapus file lama jika ada dan berbeda
        if ($old_doc['file_path'] && $old_doc['file_path'] !== $file_path) {
            $old_file_path = __DIR__ . '/../../' . $old_doc['file_path'];
            if (file_exists($old_file_path)) {
                unlink($old_file_path);
            }
        }
    }
    
    // Mulai transaksi
    $pdo->beginTransaction();
    
    try {
        // Update database
        $stmt = $pdo->prepare("
            UPDATE documents SET 
                title = ?, 
                slug = ?, 
                category = ?, 
                unit_owner = ?, 
                status = ?, 
                visibility = ?, 
                file_path = ?, 
                file_name_original = ?, 
                mime_type = ?, 
                file_size = ?, 
                file_hash = ?, 
                notes = ?, 
                effective_date = ?,
                updated_at = NOW()
            WHERE id = ?
        ");
        
        $result = $stmt->execute([
            $title,
            $slug,
            $category,
            $unit_owner,
            $status,
            $visibility,
            $file_path,
            $file_name_original,
            $mime_type,
            $file_size,
            $file_hash,
            $notes,
            $effective_date,
            $id
        ]);
        
        if (!$result) {
            throw new Exception('Gagal memperbarui data');
        }
        
        // Commit transaksi
        $pdo->commit();
        
        // Log aktivitas (setelah commit)
        try {
            $log_stmt = $pdo->prepare("
                INSERT INTO activity_logs (user_id, action, description, created_at) 
                VALUES (?, 'update_document', ?, NOW())
            ");
            $log_stmt->execute([
                $_SESSION['user_id'],
                "Memperbarui dokumen: {$title}"
            ]);
        } catch (Exception $e) {
            // Log error tapi tidak perlu throw
            error_log("Error logging activity: " . $e->getMessage());
        }
        
        $_SESSION['success'] = 'Dokumen berhasil diperbarui';
        header('Location: ../dokumen.php');
        exit;
        
    } catch (Exception $e) {
        // Rollback
        $pdo->rollBack();
        
        // Hapus file baru jika gagal
        if (isset($full_path) && file_exists($full_path) && $full_path !== $old_doc['file_path']) {
            unlink($full_path);
        }
        
        throw $e;
    }
    
} catch (Exception $e) {
    $_SESSION['error'] = $e->getMessage();
    
    // Log error
    error_log("Error dokumen_edit.php: " . $e->getMessage());
    
    header('Location: ../dokumen.php');
    exit;
}