<?php

use App\Http\Controllers\ProfileController;
use App\Http\Controllers\HomeController;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\OwnerRegistrationController;
use App\Http\Controllers\PageController;
use Illuminate\Http\Request;
use App\Models\Ticket;
use App\Models\TicketReply;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use App\Mail\TicketCreatedMail;
use App\Models\WebSetting;
use App\Models\User;
use App\Http\Controllers\QuotaTransactionController;

// ==========================================
// 1. ROUTE APLIKASI NGEKOSYUK
// ==========================================

// Halaman Utama Beranda 
Route::get('/', [HomeController::class, 'index'])->name('home');

// Halaman Pencarian (FILTER) -> TAMBAHKAN INI
Route::get('/cari-kos', [HomeController::class, 'search'])->name('search');

// Halaman Invoice / Tiket Survei
Route::get('/invoice/{transaction_code}', [HomeController::class, 'invoice'])->name('kos.invoice');


// ==========================================
// 2. SISTEM TIKET & HALAMAN STATIS 
// ==========================================

// RUTE 1: Menampilkan Halaman Hubungi Kami (GET)
Route::get('/p/kontak', function () {
    $setting = WebSetting::first();
    return view('frontend.contact', compact('setting'));
})->name('contact');

// ==========================================
// RUTE 2: Memproses Form Sistem Tiket (POST)
// ==========================================
Route::post('/p/kontak', function (Request $request) {
    // 1. Validasi Input 
    $request->validate([
        'name' => 'required|string|max:255',
        'email' => 'required|email|max:255',
        'category' => 'required|string|max:255',
        'subject' => 'nullable|string|max:255',
        'message' => 'required|string',
    ]);

    // 2. LOGIKA CERDAS: Tentukan Status Pengguna
    $userIdToSave = null;
    $userStatus = 'guest'; // Default: Tamu tidak terdaftar

    if (Auth::check()) {
        // KONDISI 3: Pengguna sedang Login
        $userIdToSave = Auth::id();
        $userStatus = 'logged_in';
    } else {
        // Cek apakah email tamu ini ada di database User
        $existingUser = User::where('email', $request->email)->first();
        if ($existingUser) {
            // KONDISI 2: Email terdaftar, tapi dia lupa belum login
            $userIdToSave = $existingUser->id;
            $userStatus = 'registered_logged_out';
        }
    }

    // 3. Buat Tiket Induk 
    $ticket = Ticket::create([
        'name' => $request->name,
        'email' => $request->email,
        'category' => $request->category,
        'subject' => $request->subject ?? 'Pertanyaan Layanan',
        'user_id' => $userIdToSave,
    ]);

    // 4. Simpan Isi Pesan
    TicketReply::create([
        'ticket_id' => $ticket->id,
        'user_id' => $userIdToSave,
        'is_admin' => false,
        'message' => $request->message,
    ]);

    // 5. EKSEKUSI EMAIL & NOTIFIKASI BERDASARKAN STATUS
    $pesanNotifikasi = "";

    if ($userStatus === 'guest') {
        // [Opsi 1] Tamu Murni: Kirim Email + Notif Cek Email
        try {
            Mail::to($ticket->email)->send(new TicketCreatedMail($ticket));
        } catch (\Exception $e) {
            // Abaikan jika error SMTP
        }
        $pesanNotifikasi = "Pesan berhasil terkirim! Nomor tiket Anda: {$ticket->ticket_number}. Tautan untuk memantau balasan telah kami kirimkan ke email Anda.";
    } elseif ($userStatus === 'registered_logged_out') {
        // [Opsi 2] Punya Akun (Lupa Login): TANPA Email + Notif Suruh Login
        $pesanNotifikasi = "Pesan berhasil terkirim! Nomor tiket Anda: {$ticket->ticket_number}. Email Anda telah terdaftar di sistem kami, silakan Masuk (Login) untuk memantau balasan di menu Dasbor.";
    } else {
        // [Opsi 3] Sudah Login: TANPA Email + Notif Cek Dasbor
        $pesanNotifikasi = "Pesan berhasil terkirim! Nomor tiket Anda: {$ticket->ticket_number}. Silakan cek riwayat tiket dan pantau balasan di menu Dasbor Anda.";
    }

    return back()->with('success', $pesanNotifikasi);
})->name('contact.submit');

// RUTE 3: Menampilkan Halaman Obrolan Tiket (Frontend)
Route::get('/tiket/{ticket_number}', function ($ticket_number, Request $request) {
    $ticket = Ticket::with('replies.user')->where('ticket_number', $ticket_number)->firstOrFail();

    $isAuthorized = false;

    if (Auth::check()) {
        if (Auth::user()->hasRole(['super_admin', 'Admin']) || Auth::id() === $ticket->user_id) {
            $isAuthorized = true;
        }
    }

    if (!$isAuthorized && $request->query('token') === $ticket->token) {
        $isAuthorized = true;
    }

    if (!$isAuthorized) {
        abort(403, 'Akses Ditolak. Anda tidak memiliki izin untuk melihat tiket ini.');
    }

    return view('frontend.ticket_chat', compact('ticket'));
})->name('ticket.show');


// RUTE 4: Memproses Balasan di Halaman Obrolan (Frontend)
Route::post('/tiket/{ticket_number}/reply', function ($ticket_number, Request $request) {
    $ticket = Ticket::where('ticket_number', $ticket_number)->firstOrFail();

    // 1. Cek Otorisasi (Keamanan)
    $isAuthorized = false;
    if (Auth::check()) {
        if (Auth::user()->hasRole(['super_admin', 'Admin']) || Auth::id() === $ticket->user_id) {
            $isAuthorized = true;
        }
    }
    if (!$isAuthorized && $request->query('token') === $ticket->token) {
        $isAuthorized = true;
    }

    if (!$isAuthorized) {
        abort(403, 'Akses Ditolak.');
    }

    if ($ticket->status === 'closed') {
        return back()->with('error', 'Tiket sudah ditutup, tidak dapat membalas pesan.');
    }

    // 2. Validasi Input (Termasuk gambar)
    $request->validate([
        'message' => 'required|string',
        'attachment' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
    ]);

    // 3. Simpan Gambar Jika Ada
    $attachmentPath = null;
    if ($request->hasFile('attachment')) {
        $attachmentPath = $request->file('attachment')->store('ticket-attachments', 'public');
    }

    // 4. Buat Balasan
    TicketReply::create([
        'ticket_id' => $ticket->id,
        'user_id' => Auth::check() ? Auth::id() : null,
        'is_admin' => false,
        'message' => $request->message,
        'attachment' => $attachmentPath, // Menyimpan path ke database
    ]);

    // 5. Update Status Tiket
    $ticket->update([
        'status' => 'open',
        'updated_at' => now(),
    ]);

    return back()->with('success', 'Balasan Anda berhasil dikirim!');
})->name('ticket.reply');


// ==========================================
// 3. HALAMAN PAGE & FAQ
// ==========================================
Route::get('/p/tentang-kami', function () {
    return view('frontend.about');
})->name('about');

Route::get('/p/faq', function () {
    return view('frontend.faq');
})->name('faq');

Route::get('/p/{slug}', [PageController::class, 'show'])->name('page.show');



// ==========================================
// 4. AUTH & PROPERTI KOS
// ==========================================

Route::middleware('auth')->group(function () {
    Route::get('/{category}/{slug}/book', [HomeController::class, 'book'])->name('kos.book');
    Route::post('/{category}/{slug}/book', [HomeController::class, 'storeBook'])->name('kos.book.store');
    Route::post('/invoice/{booking_code}/confirm', [HomeController::class, 'confirmSurvey'])->name('kos.confirm');
    Route::get('/owner/quota/invoice/{invoice_code}', [QuotaTransactionController::class, 'showInvoice'])->name('owner.quota.invoice');
    Route::post('/owner/quota/invoice/{invoice_code}/upload', [QuotaTransactionController::class, 'uploadProof'])->name('owner.quota.upload');
});

// Detail Properti (WAJIB ditaruh paling bawah)
Route::get('/{category}/{slug}', [HomeController::class, 'show'])->name('kos.show');



// ==========================================
// 5. ROUTE BAWAAN LARAVEL BREEZE (Dasbor)
// ==========================================
Route::get('/dashboard', function () {
    $user = auth()->user();

    if ($user->hasRole(['Superadmin', 'Admin', 'Owner'])) {
        return redirect('/admin');
    }

    // AMBIL DATA TIKET: Tarik tiket milik tenant ini, urutkan dari yang terbaru
    $tickets = Ticket::where('user_id', $user->id)
        ->orderBy('created_at', 'desc')
        ->get();

    // Kirim data $tickets ke tampilan (view)
    return view('dashboard', compact('tickets'));
})->middleware(['auth', 'verified'])->name('dashboard');

Route::middleware('auth')->group(function () {
    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});

Route::get('/daftar-owner', [OwnerRegistrationController::class, 'create'])->name('owner.register');
Route::post('/daftar-owner', [OwnerRegistrationController::class, 'store'])->name('owner.register.store');

require __DIR__ . '/auth.php';
