<?php

namespace App\Http\Controllers;

use App\Models\Questionnaire;
use App\Models\Response;
use App\Models\MessageLog;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Carbon\Carbon;

class KuisionerController extends Controller
{
    public function index()
    {
        $questions = Questionnaire::where('is_active', true)->get();

        return Inertia::render('Kuisioner', [
            'questions' => $questions,
            'success' => session('success'),
        ]);
    }

    public function getDashboardStats()
    {
        $totalKuisioner = Questionnaire::count();
        $totalPengunjung = Response::distinct('phone_number')->count();
        $kuisionerTerisi = Response::whereNotNull('answer')->count();

        $chartData = Response::selectRaw('DATE(created_at) as date, count(*) as value')
            ->groupBy('date')
            ->orderBy('date')
            ->get()
            ->map(function ($item) {
                return [
                    'date' => Carbon::parse($item->date)->format('Y-m-d'),
                    'value' => $item->value,
                ];
            });

        return Inertia::render('dashboard', [
            'totalKuisioner' => $totalKuisioner,
            'totalPengunjung' => $totalPengunjung,
            'kuisionerTerisi' => $kuisionerTerisi,
            'chartData' => $chartData,
        ]);
    }

    public function getUsersWhoFilledQuestionnaire()
    {
        $users = Response::select('phone_number')->distinct()->get();

        return Inertia::render('UsersList', [
            'users' => $users,
        ]);
    }

    public function viewQuestionnaireAnswers($questionnaireId)
    {
        $questionnaire = Questionnaire::with('responses')->find($questionnaireId);

        if (!$questionnaire) {
            return redirect()->route('kuisioner.index')->with('error', 'Kuisioner tidak ditemukan.');
        }

        return Inertia::render('QuestionnaireAnswers', [
            'questionnaire' => $questionnaire,
        ]);
    }

    public function viewAnswerDetails($phoneNumber)
    {
        $answers = Response::with('question')
            ->where('phone_number', $phoneNumber)
            ->get();

        return Inertia::render('JawabanKuisioner', [
            'phone_number' => $phoneNumber,
            'answers' => $answers,
        ]);
    }


    public function submit(Request $request)
    {
        $data = $request->validate([
            'phone_number' => 'required|numeric|digits_between:10,15',
            'answers' => 'required|array|min:1',
            'answers.*.question_id' => 'required|exists:questionnaires,id',
            'answers.*.answer' => 'required|string|max:255',
        ]);

        if (!preg_match('/^(0|\+62|62)/', $data['phone_number'])) {
            return back()->withErrors(['phone_number' => 'Nomor harus diawali dengan 0 atau +62.']);
        }

        $responses = collect($data['answers'])->map(function ($answer) use ($data) {
            return [
                'phone_number' => $data['phone_number'],
                'question_id' => $answer['question_id'],
                'answer' => $answer['answer'],
                'created_at' => now(),
                'updated_at' => now(),
            ];
        })->toArray();

        Response::insert($responses);

        MessageLog::create([
            'phone_number' => $data['phone_number'],
            'message' => 'Terima kasih telah mengisi kuisioner RS kami!',
            'status' => 'SENT',
        ]);

        // Kirim WhatsApp
        $waResponse = $this->sendWaMessage(
            $data['phone_number'],
            'Halo, terima kasih banyak telah meluangkan waktu untuk mengisi kuisioner kepuasan pelayanan kami di RS. Masukan Anda sangat berarti bagi kami untuk terus meningkatkan kualitas pelayanan. Semoga Anda sehat selalu! 💙🙏'
        );

        dd($waResponse);
    }

    private function sendWaMessage($phone, $message)
    {
        // Format nomor jadi 62xxxxxxxxxxx
        $phone = preg_replace('/^\+62/', '62', $phone);
        $phone = preg_replace('/^0/', '62', $phone);

        // API key dan sender bisa kamu simpan di .env
        $apiKey = config('services.wa.api_key', 'ISI_API_KEY_KAMU');
        $sender = config('services.wa.sender', '6281112300343');

        $url = "https://wa.codeucil.my.id/send-message?api_key={$apiKey}&sender={$sender}&number={$phone}&message=" . urlencode($message) . "&footer=RSUD";

        try {
            $client = new \GuzzleHttp\Client();
            $response = $client->get($url);
            return json_decode($response->getBody(), true);
        } catch (\Exception $e) {
            \Log::error('WA Error: ' . $e->getMessage());
            return ['status' => false, 'msg' => 'Gagal kirim WA: ' . $e->getMessage()];
        }
    }
}
