<?php

header('Content-Type: application/json');
ob_start();

$response = ['success' => false, 'message' => 'Gagal memperbarui informasi.', 'errors' => []];

// Sertakan file konfigurasi dan dependensi lainnya
// Gunakan @ untuk menekan warning jika file tidak ada, tapi kita akan cek $pdo nanti
@include_once __DIR__ . '/../../../config/config.php';
@include_once __DIR__ . '/../../../includes/session.php';
@include_once __DIR__ . '/../../../lib/Auth.php';
@include_once __DIR__ . '/../../../includes/functions.php';
@include_once __DIR__ . '/../../../includes/db_connect.php'; 

// Cek dependensi penting
if (!defined('PUBLIC_ROOT') || !defined('BASE_URL')) {
    $response['message'] = 'Kesalahan konfigurasi server (konstanta tidak ditemukan).';
    http_response_code(500);
    ob_end_clean(); 
    echo json_encode($response);
    exit;
}

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

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

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

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)) {
    if (!mkdir(UPLOAD_DIR, 0775, true)) {
        error_log("Failed to create upload directory: " . UPLOAD_DIR);
        $response['message'] = 'Gagal membuat direktori upload.';
        http_response_code(500);
        ob_end_clean();
        echo json_encode($response);
        exit;
    }
} elseif (!is_writable(UPLOAD_DIR)) {
    error_log("Upload directory is not writable: " . UPLOAD_DIR);
    $response['message'] = 'Direktori upload tidak dapat ditulis.';
    http_response_code(500);
    ob_end_clean();
    echo json_encode($response);
    exit;
}


$uploadedFilenameTemp = null; 

try {
    $infoId = filter_input(INPUT_POST, 'info_id', FILTER_VALIDATE_INT);
    if (!$infoId) {
        http_response_code(400);
        throw new InvalidArgumentException('ID informasi tidak valid.');
    }

    $stmtOld = $pdo->prepare("SELECT image_filename FROM informations WHERE id = :id");
    $stmtOld->bindParam(':id', $infoId, PDO::PARAM_INT);
    $stmtOld->execute();
    $oldImageFilename = $stmtOld->fetchColumn();

    $title = sanitize_input($_POST['title'] ?? '');
    $content = $_POST['content'] ?? '';
    $status = sanitize_input($_POST['status'] ?? 'active');
    $removeImageFlag = filter_input(INPUT_POST, 'remove_image', FILTER_VALIDATE_INT);
    $newImageFilename = $oldImageFilename; 

    $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.';
    }

    $fileUploaded = false;
    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)) {
                $uploadedFilenameTemp = $newFileName;
                $fileUploaded = true;
            } 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 ($removeImageFlag == 1 && !$fileUploaded) {
        $newImageFilename = null;
    } elseif ($fileUploaded) {
        $newImageFilename = $uploadedFilenameTemp;
    }
    if (!empty($errors)) {
        http_response_code(400);
        $response['message'] = 'Periksa kembali input Anda.';
        $response['errors'] = $errors;
        if ($uploadedFilenameTemp && file_exists(UPLOAD_DIR . $uploadedFilenameTemp)) {
            unlink(UPLOAD_DIR . $uploadedFilenameTemp);
        }
        ob_end_clean();
        echo json_encode($response);
        exit;
    }

    $sql = "UPDATE informations SET title = :title, content = :content, image_filename = :image, status = :status, updated_at = NOW() WHERE id = :id";
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':title', $title);
    $stmt->bindParam(':content', $content);
    $stmt->bindParam(':image', $newImageFilename); 
    $stmt->bindParam(':status', $status);
    $stmt->bindParam(':id', $infoId, PDO::PARAM_INT);

    if ($stmt->execute()) {
        if (($fileUploaded || $removeImageFlag == 1) && $oldImageFilename && file_exists(UPLOAD_DIR . $oldImageFilename)) {
             if ($oldImageFilename !== $newImageFilename) { 
                unlink(UPLOAD_DIR . $oldImageFilename);
             }
        }
        $response['success'] = true;
        $response['message'] = 'Informasi berhasil diperbarui.';
    } else {
        http_response_code(500);
        $response['message'] = 'Gagal memperbarui informasi di database.';
        if ($uploadedFilenameTemp && file_exists(UPLOAD_DIR . $uploadedFilenameTemp)) {
            unlink(UPLOAD_DIR . $uploadedFilenameTemp);
        }
    }

} catch (InvalidArgumentException $e) {
    http_response_code(400);
    $response['message'] = $e->getMessage();
    if (isset($uploadedFilenameTemp) && $uploadedFilenameTemp && file_exists(UPLOAD_DIR . $uploadedFilenameTemp)) { unlink(UPLOAD_DIR . $uploadedFilenameTemp); }
} catch (\PDOException $e) {
    error_log("Admin Update Information DB Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan database.";
    http_response_code(500);
    if (isset($uploadedFilenameTemp) && $uploadedFilenameTemp && file_exists(UPLOAD_DIR . $uploadedFilenameTemp)) { unlink(UPLOAD_DIR . $uploadedFilenameTemp); }
} catch (\Throwable $e) {
    error_log("Admin Update 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($uploadedFilenameTemp) && $uploadedFilenameTemp && file_exists(UPLOAD_DIR . $uploadedFilenameTemp)) { unlink(UPLOAD_DIR . $uploadedFilenameTemp); }
}

ob_end_clean();
echo json_encode($response);
exit;
?>
