<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;


class UlasanController extends Controller
{
    public function ulasanPage(Request $request)
    {
        $query = \App\Models\Survey::whereNotNull('ulasan')
            ->where('ulasan', '!=', '');

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where('title', 'like', "%{$search}%");
        }

        $surveys = $query->orderBy('updated_at', 'desc')->get();

        return view('admin.surveys.ulasan', compact('surveys'));
    }

    public function updateUlasan(Request $request, $id)
    {
        $survey = \App\Models\Survey::findOrFail($id);

        $survey->ulasan = $request->ulasan;
        $survey->save();

        return back()->with('success', 'Ulasan berjaya dikemaskini!');
    }

    public function downloadCSV()
    {
        $surveys = \App\Models\Survey::whereNotNull('ulasan')
            ->where('ulasan', '!=', '')
            ->orderBy('updated_at', 'desc')
            ->get();

        $filename = "keputusan_postmortem" . date('Ymd_His') . ".csv";
        $handle = fopen('php://output', 'w');

        // Add UTF-8 BOM for Excel compatibility
        fprintf($handle, chr(0xEF) . chr(0xBB) . chr(0xBF));

        // Header
        fputcsv($handle, ['ID', 'Tarikh Kemaskini', 'Tajuk Borang', 'Ulasan']);

        // Data
        foreach ($surveys as $survey) {
            fputcsv($handle, [
                $survey->id,
                $survey->updated_at->format('d/m/Y'),
                $survey->title,
                $survey->ulasan
            ]);
        }

        fclose($handle);

        return response()->streamDownload(function () use ($handle) {
            // Already handled by fputcsv to php://output
        }, $filename, [
            'Content-Type' => 'text/csv',
        ]);
    }
}
