<?php

namespace App\Http\Controllers;

use App\Models\Jasa;
use App\Models\Address;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class JasaController extends Controller
{
    /**
     * Menampilkan daftar riwayat jasa service UNTUK USER
     */
    public function index()
    {
        $jasas = Jasa::with('address')
            ->where('user_id', Auth::id())
            ->latest()
            ->paginate(10);
            
        return view('jasa.index', compact('jasas'));
    }

    /**
     * Menampilkan daftar riwayat jasa service UNTUK ADMIN
     */
    public function adminIndex()
    {
        // Admin bisa melihat semua data dari seluruh user
        $jasas = Jasa::with(['address.province', 'address.regency', 'address.district', 'address.village', 'user'])
            ->latest()
            ->paginate(15);
            
        return view('admin.jasa.index', compact('jasas'));
    }

    /**
     * Menampilkan form service dengan desain modern & dinamis
     */
    public function create()
    {
        $addresses = Address::where('user_id', Auth::id())->get();
        
        // Ambil pesanan yang sedang berjalan (pending atau proses)
        $activeJasas = Jasa::where('user_id', Auth::id())
                            ->whereIn('status', ['pending', 'proses', 'selesai'])
                            ->latest()
                            ->get();

        // Data statistik untuk sidebar
        $jasa_avg_rating = round(Jasa::whereNotNull('rating')->avg('rating'), 1) ?: '5.0';
        $jasa_total_reviews = Jasa::whereNotNull('rating')->count();

        return view('jasa.create', compact('addresses', 'activeJasas', 'jasa_avg_rating', 'jasa_total_reviews'));
    }

    /**
     * Memproses data service dan redirect ke WhatsApp
     */
    public function kirimWa(Request $request)
    {
        $request->validate([
            'address_id'         => 'required_if:jenis_layanan,Panggilan Teknisi|nullable|exists:addresses,id',
            'merek_printer'      => 'required|string',
            'tipe_printer'       => 'required|string',
            'kategori_keluhan'   => 'required|string',
            'deskripsi_masalah'  => 'required|string',
            'foto_video'         => 'nullable|file|mimes:jpg,jpeg,png,mp4,mov|max:5120',
            'pernah_diservis'    => 'required|string',
            'jenis_layanan'      => 'required|string',
        ]);

        $user = Auth::user();
        $alamat = null;
        if ($request->jenis_layanan == 'Panggilan Teknisi') {
            $alamat = Address::findOrFail($request->address_id);
        }

        $namaMedia = null;
        if ($request->hasFile('foto_video')) {
            $namaMedia = time() . '.' . $request->file('foto_video')->extension();
            // Simpan ke disk 'public' agar masuk ke folder storage/app/public/service
            $request->file('foto_video')->storeAs('service', $namaMedia, 'public');
        }

        $jasa = Jasa::create([
            'user_id'            => $user->id,
            'address_id'         => $request->address_id,
            'merek_printer'      => $request->merek_printer,
            'tipe_printer'       => $request->tipe_printer,
            'kategori_keluhan'   => $request->kategori_keluhan,
            'deskripsi_masalah'  => $request->deskripsi_masalah,
            'foto_video_kondisi' => $namaMedia,
            'pernah_diservis'    => $request->pernah_diservis,
            'jenis_layanan'      => $request->jenis_layanan,
            'status'             => 'pending',
        ]);

        $lokasiInfo = $request->jenis_layanan == 'Antar ke Toko' 
            ? "Antar ke Toko (Menuju Workshop)"
            : "Panggilan Teknisi Ke Lokasi\n     📍 *Alamat:* " . ($alamat ? $alamat->alamat_lengkap : 'N/A');

        // Menggunakan Preview Link agar muncul Gambar di WhatsApp
        $mediaLink = $namaMedia ? "🔗 " . route('jasa.preview', $jasa->id) : "📄 (Tidak ada lampiran foto/video)";

        $pesan = "Halo Tim Admin! 👋\n" .
                 "Saya ingin mengajukan layanan perbaikan printer. Berikut adalah detail informasinya:\n\n" .
                 "🎫 *INFORMASI TIKET*\n" .
                 " ▫️ *ID Tiket:* #SVR-{$jasa->id}\n" .
                 " ▫️ *Nama Pengirim:* {$user->name}\n" .
                 " ▫️ *No. WhatsApp:* " . ($user->phone ?? '-') . "\n\n" .
                 "🖨️ *SPESIFIKASI UNIT*\n" .
                 " ▫️ *Merek Printer:* {$request->merek_printer}\n" .
                 " ▫️ *Tipe / Seri:* {$request->tipe_printer}\n" .
                 " ▫️ *Riwayat Servis:* {$request->pernah_diservis}\n\n" .
                 "🔥 *DETAIL KENDALA*\n" .
                 " ▫️ *Masalah Utama:* {$request->kategori_keluhan}\n" .
                 " ▫️ *Penjelasan:* _{$request->deskripsi_masalah}_\n\n" .
                 "🚚 *METODE LAYANAN*\n" .
                 " ▫️ *Pilihan:* {$lokasiInfo}\n\n" .
                 "📎 *LAMPIRAN KONDISI*\n" .
                 " {$mediaLink}\n\n" .
                 "Mohon dibantu untuk pengecekan teknisi dan estimasi biayanya ya. Terima kasih banyak! 🙏";

        $waNumber = \App\Models\Setting::get('shop_wa_number', '81234567890');
        $waNumber = preg_replace('/[^0-9]/', '', $waNumber);
        // Format to Indonesian prefix (+62)
        if (str_starts_with($waNumber, '0')) {
            $waNumber = '62' . substr($waNumber, 1);
        } else if (!str_starts_with($waNumber, '62')) {
            $waNumber = '62' . $waNumber;
        }
        $url = "https://wa.me/{$waNumber}?text=" . urlencode($pesan);

        // Langsung redirect ke WA, data sudah tersimpan di DB
        return redirect()->away($url);
    }

    /**
     * Update Status Service (AJAX)
     */
    public function updateStatus(Request $request, $id)
    {
        $jasa = Jasa::findOrFail($id);
        
        $request->validate([
            'status' => 'required|in:pending,proses,selesai,batal'
        ]);

        $jasa->update(['status' => $request->status]);

        return response()->json([
            'success' => true,
            'message' => 'Status berhasil diperbarui ke: ' . strtoupper($request->status)
        ]);
    }

    /**
     * Preview Media Page (Agar Link di WA muncul Gambar)
     */
    public function previewMedia($id)
    {
        $jasa = Jasa::findOrFail($id);
        return view('jasa.preview', compact('jasa'));
    }

    /**
     * Hapus Riwayat Jasa (AJAX)
     */
    public function destroy($id)
    {
        $jasa = Jasa::where('id', $id)->first();
        
        // Admin bisa hapus semuanya, User hanya bisa hapus miliknya
        if (Auth::user()->role === 'admin' || $jasa->user_id === Auth::id()) {
            if ($jasa) {
                $jasa->delete();
                return response()->json(['success' => true]);
            }
        }
        
        return response()->json(['success' => false], 403);
    }
    /**
     * Menyimpan rating dan testimoni dari pelanggan
     */
    public function submitRating(Request $request, $id)
    {
        $jasa = Jasa::where('id', $id)->where('user_id', Auth::id())->firstOrFail();
        
        if (strtolower($jasa->status) !== 'selesai') {
            return back()->with('error', 'Layanan belum selesai, Anda belum bisa memberikan rating.');
        }

        $request->validate([
            'rating'    => 'required|integer|min:1|max:5',
            'testimoni' => 'nullable|string|max:500'
        ]);

        $jasa->update([
            'rating'    => $request->rating,
            'testimoni' => $request->testimoni
        ]);

        return back()->with('success', 'Terima kasih atas penilaian Anda!');
    }
}