<?php

namespace App\Http\Controllers;

use App\Models\Sewa;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class RiwayatController extends Controller
{
    public function index()
    {
        $sewas = Sewa::with(['paket', 'kota'])
            ->where('user_id', Auth::id())
            ->where('status', '!=', 'draft')
            ->orderBy('created_at', 'desc')
            ->get();

        return view('riwayat', compact('sewas'));
    }

    public function updateStatus(Request $request, $id)
    {
        if (Auth::user()->tipe_pengguna !== 'admin') {
            return redirect()->route('dashboard')->with('error', 'Akses ditolak.');
        }

        $request->validate([
            'status' => 'required|in:completed'
        ]);

        $sewa = Sewa::findOrFail($id);

        if ($sewa->status !== 'confirmed') {
            return back()->with('error', 'Status hanya bisa diubah jika saat ini adalah confirmed.');
        }

        $sewa->status = $request->status;
        $sewa->save();

        return back()->with('success', 'Status berhasil diperbarui menjadi completed.');
    }

    public function hapus($id)
    {
        $sewa = Sewa::findOrFail($id);

        if ($sewa->user_id != Auth::id()) {
            return redirect()->route('riwayat')
                ->with('error', 'Anda tidak memiliki akses untuk menghapus pesanan ini.');
        }

        if (!in_array($sewa->status, ['completed', 'dibatalkan'])) {
            return redirect()->route('riwayat')
                ->with('error', 'Hanya pesanan yang sudah selesai atau dibatalkan yang dapat dihapus.');
        }

        if ($sewa->bukti_pembayaran) {
            Storage::disk('public')->delete($sewa->bukti_pembayaran);
        }
        if ($sewa->foto_jaminan) {
            Storage::disk('public')->delete($sewa->foto_jaminan);
        }

        $sewa->delete();

        return redirect()->route('riwayat')
            ->with('success', 'Riwayat pesanan berhasil dihapus.');
    }
}
