<?php

namespace App\Http\Controllers;

use App\Models\Titip;
use App\Models\Distribution;
use Illuminate\Http\Request;
use Carbon\Carbon;

class TitipController extends Controller
{
    public function index(Request $request)
    {
        $search = $request->input('search');
        $status = $request->input('status');

        $query = Titip::with(['participant', 'entrustee']);

        if ($search) {
            $query->where(function($q) use ($search) {
                $q->whereHas('participant', function($qp) use ($search) {
                    $qp->where('nama', 'like', "%{$search}%")
                       ->orWhere('no_kupon', 'like', "%{$search}%");
                })->orWhereHas('entrustee', function($qe) use ($search) {
                    $qe->where('nama', 'like', "%{$search}%")
                       ->orWhere('no_kupon', 'like', "%{$search}%");
                });
            });
        }

        if ($status) {
            $query->where('status', $status);
        }

        $titips = $query->orderBy('created_at', 'desc')->paginate(15)->withQueryString();

        return view('titip.index', compact('titips'));
    }

    public function updateStatus(Request $request, $id)
    {
        $titip = Titip::findOrFail($id);
        
        $request->validate([
            'status' => 'required|in:Pending,Diproses,Selesai',
        ]);

        $status = $request->input('status');
        $takenAt = $status === 'Selesai' ? Carbon::now() : null;

        $titip->update([
            'status' => $status,
            'taken_at' => $takenAt,
        ]);

        // Keep distribusis status in sync if needed (though it remains 'Titip')
        if ($status === 'Selesai') {
            Distribution::where('qurban_participant_id', $titip->qurban_participant_id)->update([
                'scanned_at' => Carbon::now(),
            ]);
        }

        return redirect()->back()->with('success', "Status titipan untuk {$titip->participant->nama} berhasil diubah ke {$status}.");
    }
}
