<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\{WorkOrder, WorkOrderPhoto, Client, User, ActivityLog};
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class WorkOrderController extends Controller
{
    public function index(Request $request)
    {
        $q = WorkOrder::with(['client','assignedTo'])->orderByDesc('created_at');
        if ($request->status)   $q->where('status', $request->status);
        if ($request->division) $q->where('division', $request->division);
        if ($request->search)   $q->where(fn($s) => $s->where('wo_number','like',"%{$request->search}%")->orWhere('item_name','like',"%{$request->search}%")->orWhere('customer_name','like',"%{$request->search}%"));
        $workorders  = $q->paginate(20)->withQueryString();
        return view('admin.workorders.index', compact('workorders'));
    }

    public function create()
    {
        $clients     = Client::where('is_active',1)->orderBy('name')->get();
        $technicians = User::where('role','technician')->where('is_active',1)->get();
        return view('admin.workorders.create', compact('clients','technicians'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'client_id'      => 'nullable|exists:clients,id',
            'division'       => 'required|in:FixLab,Havva',
            'type'           => 'required|in:repair,installation',
            'item_name'      => 'required|string',
            'item_brand'     => 'nullable|string',
            'item_serial'    => 'nullable|string',
            'reported_issue' => 'required|string',
            'customer_name'  => 'nullable|string',
            'customer_phone' => 'nullable|string',
            'assigned_to'    => 'nullable|exists:users,id',
            'notes'          => 'nullable|string',
        ]);
        $data['wo_number']   = WorkOrder::generateNumber();
        $data['created_by']  = auth()->id();
        $data['status']      = 'received';
        $data['received_at'] = now();

        $wo = WorkOrder::create($data);

        // Handle before photos
        if ($request->hasFile('photos')) {
            foreach ($request->file('photos') as $photo) {
                $path = $photo->storeAs('workorder-photos', Str::uuid().'.'.$photo->extension(), 'public');
                $wo->photos()->create(['path'=>$path,'type'=>'before']);
            }
        }

        ActivityLog::log('workorder','created',"Work Order #{$wo->wo_number} dibuat", $wo);
        return redirect()->route('admin.workorders.show', $wo)->with('success','Work Order dibuat.');
    }

    public function show(WorkOrder $workorder)
    {
        $workorder->load(['client','assignedTo','photos']);
        $technicians = User::where('role','technician')->where('is_active',1)->get();
        return view('admin.workorders.show', compact('workorder','technicians'));
    }

    public function edit(WorkOrder $workorder)
    {
        $clients     = Client::where('is_active',1)->orderBy('name')->get();
        $technicians = User::where('role','technician')->where('is_active',1)->get();
        return view('admin.workorders.edit', compact('workorder','clients','technicians'));
    }

    public function update(Request $request, WorkOrder $workorder)
    {
        $data = $request->validate([
            'assigned_to'     => 'nullable|exists:users,id',
            'diagnosis'       => 'nullable|string',
            'action_taken'    => 'nullable|string',
            'estimated_cost'  => 'nullable|numeric|min:0',
            'final_cost'      => 'nullable|numeric|min:0',
            'spareparts'      => 'nullable|array',
            'notes'           => 'nullable|string',
        ]);
        $workorder->update($data);
        return back()->with('success','Work Order diperbarui.');
    }

    public function changeStatus(Request $request, WorkOrder $workorder)
    {
        $request->validate(['status'=>'required|in:received,diagnosed,waiting_approval,in_repair,done,delivered,cancelled']);
        $update = ['status'=>$request->status];
        if ($request->status === 'delivered') {
            $update['delivered_at'] = now();
            if ($request->signature) $update['delivery_signature'] = $request->signature;
        }
        $workorder->update($update);
        ActivityLog::log('workorder','status_changed',"WO #{$workorder->wo_number}: {$request->status}", $workorder);
        return back()->with('success','Status diperbarui.');
    }

    public function uploadPhoto(Request $request, WorkOrder $workorder)
    {
        $request->validate(['photo'=>'required|file|mimes:jpg,jpeg,png|max:5120','type'=>'required|in:before,after,delivery']);
        $path = $request->file('photo')->storeAs('workorder-photos', Str::uuid().'.'.$request->file('photo')->extension(), 'public');
        $workorder->photos()->create(['path'=>$path,'type'=>$request->type]);
        return back()->with('success','Foto berhasil diupload.');
    }

    public function destroy(WorkOrder $workorder)
    {
        $workorder->delete();
        return redirect()->route('admin.workorders.index')->with('success','Work Order dihapus.');
    }
}
