<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Inertia\Inertia;
use App\Models\TracerStudy;
use App\Http\Controllers\LandingPageController;
use App\Http\Controllers\BiayaJurusanController;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use App\Mail\TracerStudyMail; // Gantilah dengan mail yang relevan sesuai kebutuhan
use Illuminate\Support\Facades\Storage; // Import Storage Facade
class TracerStudyController extends Controller
{
    // ==========================================================
    // FUNGSI TRACER STUDY
    // ==========================================================

    /**
     * Menampilkan halaman formulir Tracer Study berdasarkan slug kampus.
     *
     * @param string $slug Slug kampus (e.g., 'akbid', 'umiba')
     * @return \Inertia\Response
     */
    public function create(string $slug)
    {
        // 1. Ambil data dasar kampus untuk validasi dan tampilan
        $campusData = LandingPageController::getBaseCampusData($slug);
        if (!$campusData) {
            return abort(404, "Data kampus tidak ditemukan untuk slug: " . $slug);
        }

        // 2. Ambil data jurusan untuk dropdown prodi
        $jurusanData = BiayaJurusanController::getAllMajors($slug);
        
        return Inertia::render('TracerStudy/FormulirTracerStudy', [
            'campus' => $campusData,
            'slug' => $slug,
            'jurusanOptions' => $jurusanData,
        ]);
    }

    /**
     * Menyimpan data Tracer Study yang diisi oleh alumni.
     *
     * @param \Illuminate\Http\Request $request
     * @param string $slug Slug kampus yang sedang aktif (DITERIMA DARI ROUTE)
     * @return \Illuminate\Http\RedirectResponse
     */
public function store(Request $request, string $slug)
{
    // 1. Validasi Data Input
    $validatedData = $request->validate([
        'kampus' => 'required|string|max:150',        
        // 'campus_id' => 'required|string|max:150',
        'slug_kampus' => 'required|string|max:100',
        'jurusan' => 'required|string|max:150',
        'nama' => 'required|string|max:150',
        'email' => 'required|email|max:100|unique:tracer_studies,email',
        'foto' => 'nullable|image|max:2048', // Foto optional with max size of 2MB
        'tahun_lulus' => 'required|integer',
        'job' => 'nullable|string|max:255',
        'is_prestasi' => 'nullable|boolean', // Optional, default 0
    ]);

    // 2. Menyimpan data ke database Tracer Study
    try {
        // Menyimpan foto jika ada
        if ($request->hasFile('foto')) {

            $fotoPath = $request->file('foto')->store('tracer_study', 'public');

            $validatedData['foto'] = $fotoPath;
        }

        // Menyimpan data tracer study ke database
        $tracerStudy = TracerStudy::create($validatedData);

        // 3. Kirim email konfirmasi langsung menggunakan Mail
        try {
            $urlSukses = route('tracerStudy.sukses', ['slug' => $slug, 'id' => $tracerStudy->id]);
            Mail::to($tracerStudy->email)->send(new TracerStudyMail($tracerStudy, $urlSukses, LandingPageController::getBaseCampusData($slug)));
        } catch (\Throwable $mailErr) {
            Log::warning('Gagal mengirim email konfirmasi Tracer Study: ' . $mailErr->getMessage());
        }

        // 4. Redirect ke halaman sukses
        return redirect()
            ->route('tracerStudy.sukses', [
                'slug' => $slug,
                'id' => $tracerStudy->id
            ])
            ->with('success', 'Pendaftaran Tracer Study Anda berhasil disimpan! Silakan tunggu konfirmasi selanjutnya.');
    } catch (\Exception $e) {
        Log::error("Gagal menyimpan data Tracer Study: " . $e->getMessage());

        return back()
            ->withInput()
            ->with('error', 'Terjadi kesalahan saat menyimpan data. Silakan coba lagi.');
    }
}



    /**
     * Menampilkan halaman sukses setelah pendaftaran Tracer Study dengan data tertentu.
     *
     * @param string $slug Slug kampus (e.g., 'akbid', 'umiba')
     * @param int $id ID Tracer Study yang berhasil disimpan
     * @return \Inertia\Response
     */
    public function showSuccess(string $slug, int $id)
    {
        // 1. Ambil data Tracer Study berdasarkan ID dan verifikasi slug_kampus
        $tracerStudy = TracerStudy::where('id', $id)
            ->where('slug_kampus', $slug)
            ->first();

        // 2. Ambil data kampus untuk layout
        $campusData = LandingPageController::getBaseCampusData($slug);

        if (!$tracerStudy) {
            // Jika data Tracer Study tidak ditemukan ATAU slug_kampus tidak cocok
            return Inertia::render('TracerStudy/TracerStudyNotFound', [
                'campus' => $campusData,
                'slug' => $slug,
                'errorMessage' => "Data Tracer Study dengan ID **#$id** tidak ditemukan atau tidak terdaftar di kampus ini. Silakan cek kembali tautan yang Anda gunakan.",
            ]);
        }

        // 3. Render halaman sukses jika Tracer Study ditemukan
        return Inertia::render('TracerStudy/TracerStudySukses', [
            'campus' => $campusData,
            'slug' => $slug,
            'tracerStudy' => $tracerStudy,
            'flash' => [
                'success' => session('success'),
                'tracerStudyData' => session('tracerStudyData'),
            ]
        ]);
    }

    /**
     * Menampilkan halaman Tracer Study berdasarkan slug dan id.
     *
     * @param string $slug
     * @param int $id
     * @return \Inertia\Response
     */
    public function show(string $slug, int $id)
    {
        // 1. Ambil data Tracer Study berdasarkan ID dan verifikasi slug_kampus
        $tracerStudy = TracerStudy::where('id', $id)
            ->where('slug_kampus', $slug)
            ->first();

        // 2. Ambil data kampus untuk layout
        $campusData = LandingPageController::getBaseCampusData($slug);

        if (!$tracerStudy) {
            return abort(404, "Data Tracer Study tidak ditemukan.");
        }

        return Inertia::render('TracerStudy/Detail', [
            'campus' => $campusData,
            'slug' => $slug,
            'tracerStudy' => $tracerStudy,
        ]);
    }
}
