<?php
    header('Content-Type: application/json');
    $response = ['success' => false, 'message' => 'Gagal menambahkan informasi.', 'errors' => []];

    require_once __DIR__ . '/../../../config/config.php';
    require_once __DIR__ . '/../../../includes/session.php';
    require_once __DIR__ . '/../../../lib/Auth.php';
    require_once __DIR__ . '/../../../includes/functions.php';

    if (!Auth::isLoggedIn() || $_SESSION['user_role'] !== 'admin') {
        http_response_code(403);
        $response['message'] = 'Akses ditolak.';
        echo json_encode($response);
        exit;
    }

    if (!isset($pdo) || !$pdo instanceof PDO) {
        http_response_code(500);
        error_log("PDO object not available in admin/add_information.php");
        $response['message'] = 'Koneksi database gagal.';
        echo json_encode($response);
        exit;
    }

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        $response['message'] = 'Metode request tidak valid.';
        echo json_encode($response);
        exit;
    }

    // Direktori upload
    define('UPLOAD_DIR', PUBLIC_ROOT . '/uploads/informations/');
    define('MAX_FILE_SIZE', 2 * 1024 * 1024); // 2MB
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];

    if (!is_dir(UPLOAD_DIR) && !mkdir(UPLOAD_DIR, 0775, true)) {
        http_response_code(500);
        error_log("Failed to create upload directory: " . UPLOAD_DIR);
        $response['message'] = 'Gagal membuat direktori upload.';
        echo json_encode($response);
        exit;
    }
     if (!is_writable(UPLOAD_DIR)) {
        http_response_code(500);
        error_log("Upload directory is not writable: " . UPLOAD_DIR);
        $response['message'] = 'Direktori upload tidak dapat ditulis.';
        echo json_encode($response);
        exit;
    }


    try {
        $title = sanitize_input($_POST['title'] ?? '');
        $content = $_POST['content'] ?? '';
        $status = sanitize_input($_POST['status'] ?? 'active');
        $imageFilename = null; 

        $errors = [];

        if (empty($title)) {
            $errors['info_title'] = 'Judul wajib diisi.';
        } elseif (mb_strlen($title) > 255) {
             $errors['info_title'] = 'Judul terlalu panjang (maks 255 karakter).';
        }

        if (empty($content)) {
            $errors['info_content'] = 'Konten wajib diisi.';
        }

        if (!in_array($status, ['active', 'inactive'])) {
            $errors['info_status'] = 'Status tidak valid.';
        }

        // Handle file upload
        if (isset($_FILES['info_image']) && $_FILES['info_image']['error'] == UPLOAD_ERR_OK) {
            $fileTmpPath = $_FILES['info_image']['tmp_name'];
            $fileName = $_FILES['info_image']['name'];
            $fileSize = $_FILES['info_image']['size'];
            $fileType = $_FILES['info_image']['type'];
            $fileNameCmps = explode(".", $fileName);
            $fileExtension = strtolower(end($fileNameCmps));

            if ($fileSize > MAX_FILE_SIZE) {
                $errors['info_image'] = 'Ukuran file terlalu besar (Maks 2MB).';
            } elseif (!in_array($fileType, $allowedTypes)) {
                $errors['info_image'] = 'Format file tidak diizinkan (Hanya JPG, PNG, GIF, WEBP).';
            } else {
                $newFileName = md5(time() . $fileName) . '.' . $fileExtension;
                $dest_path = UPLOAD_DIR . $newFileName;

                if (move_uploaded_file($fileTmpPath, $dest_path)) {
                    $imageFilename = $newFileName;
                } else {
                    $errors['info_image'] = 'Gagal memindahkan file yang diunggah.';
                    error_log("Failed to move uploaded file to: " . $dest_path);
                }
            }
        } elseif (isset($_FILES['info_image']) && $_FILES['info_image']['error'] != UPLOAD_ERR_NO_FILE) {
            $uploadErrors = [
                UPLOAD_ERR_INI_SIZE   => 'Ukuran file melebihi batas server.',
                UPLOAD_ERR_FORM_SIZE  => 'Ukuran file melebihi batas form.',
                UPLOAD_ERR_PARTIAL    => 'File hanya terunggah sebagian.',
                UPLOAD_ERR_CANT_WRITE => 'Gagal menulis file ke disk.',
                UPLOAD_ERR_EXTENSION  => 'Ekstensi PHP menghentikan unggahan file.',
            ];
            $errorCode = $_FILES['info_image']['error'];
            $errors['info_image'] = $uploadErrors[$errorCode] ?? 'Terjadi kesalahan saat mengunggah file.';
             error_log("File upload error code: " . $errorCode);
        }


        if (!empty($errors)) {
            http_response_code(400);
            $response['message'] = 'Periksa kembali input Anda.';
            $response['errors'] = $errors;
        } else {
            $sql = "INSERT INTO informations (title, content, image_filename, status, created_at, updated_at) VALUES (:title, :content, :image, :status, NOW(), NOW())";
            $stmt = $pdo->prepare($sql);
            $stmt->bindParam(':title', $title);
            $stmt->bindParam(':content', $content);
            $stmt->bindParam(':image', $imageFilename); 
            $stmt->bindParam(':status', $status);

            if ($stmt->execute()) {
                $response['success'] = true;
                $response['message'] = 'Informasi baru berhasil ditambahkan.';
            } else {
                http_response_code(500);
                $response['message'] = 'Gagal menambahkan informasi ke database.';
                if ($imageFilename && file_exists(UPLOAD_DIR . $imageFilename)) {
                    unlink(UPLOAD_DIR . $imageFilename);
                }
            }
        }

    } catch (\PDOException $e) {
        error_log("Admin Add Information DB Error: " . $e->getMessage());
        $response['message'] = "Terjadi kesalahan database.";
        http_response_code(500);
        if (isset($imageFilename) && $imageFilename && file_exists(UPLOAD_DIR . $imageFilename)) {
            unlink(UPLOAD_DIR . $imageFilename);
        }
    } catch (\Throwable $e) {
        error_log("Admin Add Information General Error: " . $e->getMessage());
        $response['message'] = "Terjadi kesalahan internal server.";
        if (defined('DEBUG_MODE') && DEBUG_MODE === true) { $response['debug_php'] = $e->getMessage(); }
        http_response_code(500);
        if (isset($imageFilename) && $imageFilename && file_exists(UPLOAD_DIR . $imageFilename)) {
            unlink(UPLOAD_DIR . $imageFilename);
        }
    }

    echo json_encode($response);
    exit;
    ?>
    