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

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Visit;
use App\Models\VisitPreparation;
use App\Models\VisitSparepart;

class VisitChecklistController extends Controller
{
    // Helper method to authorize with admin bypass
    private function checkVisitAccess(Visit $visit, string $action = 'view'): void
    {
        // Allow admin to access all
        if (auth()->user()->isAdmin()) {
            return;
        }
        // Otherwise use standard authorization
        $this->authorize($action, $visit);
    }

    // store preparation (H-1)
    public function storePreparation(Request $request, Visit $visit)
    {
        $this->checkVisitAccess($visit, 'update');

        $data = $request->validate([
            'need_tools' => 'required|boolean',
            'tools' => 'nullable|array',
            'notes' => 'nullable|string|max:2000',
            'spareparts' => 'nullable|array',
        ]);

        $prep = VisitPreparation::updateOrCreate([
            'visit_id' => $visit->id,
            'user_id' => auth()->id(),
        ],[
            'need_tools' => $data['need_tools'],
            'tools' => $data['tools'] ?? null,
            'notes' => $data['notes'] ?? null,
            'prepared_at' => now(),
        ]);

        // spareparts
        if (!empty($data['spareparts'])) {
            foreach ($data['spareparts'] as $sp) {
                if (empty($sp['name'])) continue;
                VisitSparepart::create([
                    'visit_id' => $visit->id,
                    'name' => $sp['name'],
                    'qty' => $sp['qty'] ?? 1,
                    'source' => $sp['source'] ?? 'stock',
                ]);
            }
        }

        return response()->json(['status'=>'ok','preparation_id'=>$prep->id]);
    }

    public function showPreparation(Visit $visit)
    {
        $this->checkVisitAccess($visit, 'view');
        $prep = VisitPreparation::where('visit_id',$visit->id)->first();
        return response()->json(['preparation'=>$prep]);
    }

    // simple mobile form view
    public function form(Visit $visit)
    {
        $this->checkVisitAccess($visit, 'view');
        return view('admin.visits.preparation', ['visit'=>$visit]);
    }

    // show check-in form (camera + gps)
    public function showCheckin(Visit $visit)
    {
        $this->checkVisitAccess($visit, 'view');
        return view('admin.visits.checkin', ['visit' => $visit]);
    }

    // store arrival photo + gps
    public function storeCheckin(Request $request, Visit $visit)
    {
        $this->checkVisitAccess($visit, 'update');

        $request->validate([
            'photo' => 'required|file|mimes:jpeg,png,jpg|max:10240',
            'lat' => 'required|numeric',
            'lng' => 'required|numeric',
            'accuracy' => 'nullable|integer',
            'met_person' => 'nullable|string|max:255',
            'condition' => 'nullable|string|in:normal,different',
            'condition_note' => 'nullable|string|max:2000',
        ]);

        try {
            $res = app(\App\Services\ImageService::class)->processAndSave($request->file('photo'), $visit, 'arrival', ['lat'=>$request->lat,'lng'=>$request->lng]);
        } catch (\Exception $e) {
            return back()->withErrors(['photo'=>'Invalid image file']);
        }

        $photo = \App\Models\VisitPhoto::create([
            'visit_id' => $visit->id,
            'user_id' => auth()->id(),
            'type' => 'arrival',
            'path' => $res['path'],
            'lat' => $request->lat,
            'lng' => $request->lng,
            'accuracy' => $request->accuracy,
            'watermark' => $res['watermark'],
        ]);

        // timestamp arrival in visit_time_start if empty
        if (empty($visit->visit_time_start)) {
            $visit->visit_time_start = now()->format('H:i:s');
            $visit->save();
        }

        return redirect()->route('admin.visits.show', $visit)->with('success','Check-in tercatat.');
    }

    // show work log UI
    public function showWork(Visit $visit)
    {
        $this->checkVisitAccess($visit, 'view');
        return view('admin.visits.work', ['visit' => $visit]);
    }

    // store before photo + initial description
    public function storeBeforePhoto(Request $request, Visit $visit)
    {
        $this->checkVisitAccess($visit, 'update');
        $request->validate([
            'photo' => 'required|file|mimes:jpeg,png,jpg|max:10240',
            'description' => 'required|string|min:30',
        ]);

        try {
            $res = app(\App\Services\ImageService::class)->processAndSave($request->file('photo'), $visit, 'before');
        } catch (\Exception $e) {
            return back()->withErrors(['photo'=>'Invalid image file']);
        }

        \App\Models\VisitPhoto::create([
            'visit_id'=>$visit->id,'user_id'=>auth()->id(),'type'=>'before','path'=>$res['path']
        ]);

        // create initial description as a log entry
        \App\Models\VisitLog::create([
            'visit_id'=>$visit->id,'user_id'=>auth()->id(),'time'=>now()->format('H:i:s'),'activity'=>$request->description
        ]);

        return redirect()->route('admin.visits.work', $visit)->with('success','Foto kondisi awal dan deskripsi tersimpan.');
    }

    // append work log (AJAX)
    public function addWorkLog(Request $request, Visit $visit)
    {
        $this->checkVisitAccess($visit, 'update');
        $data = $request->validate(['activity'=>'required|string|min:3']);
        $log = \App\Models\VisitLog::create([
            'visit_id'=>$visit->id,'user_id'=>auth()->id(),'time'=>now()->format('H:i:s'),'activity'=>$data['activity']
        ]);
        return response()->json(['status'=>'ok','log_id'=>$log->id,'time'=>$log->time,'activity'=>$log->activity]);
    }

    // store after photo (must be done before pre-pulang)
    public function storeAfterPhoto(Request $request, Visit $visit)
    {
        $this->checkVisitAccess($visit, 'update');
        $request->validate(['photo'=>'required|file|mimes:jpeg,png,jpg|max:10240']);
        try {
            $res = app(\App\Services\ImageService::class)->processAndSave($request->file('photo'), $visit, 'after');
        } catch (\Exception $e) {
            return back()->withErrors(['photo'=>'Invalid image']);
        }

        \App\Models\VisitPhoto::create(['visit_id'=>$visit->id,'user_id'=>auth()->id(),'type'=>'after','path'=>$res['path']]);
        return redirect()->route('admin.visits.work',$visit)->with('success','Foto kondisi akhir tersimpan.');
    }

    // show pre-pulang checklist
    public function showPrePulang(Visit $visit)
    {
        $this->checkVisitAccess($visit, 'update');
        return view('admin.visits.pre_pulang', ['visit'=>$visit]);
    }

    // submit pre-pulang checklist and enforce rules
    public function submitPrePulang(Request $request, Visit $visit)
    {
        $this->checkVisitAccess($visit, 'update');
        $data = $request->validate([
            'issue_resolved' => 'required|boolean',
            'tested_with_client' => 'required|boolean',
            'not_complete_reason' => 'nullable|string|max:2000',
            'tools_collected' => 'required|boolean',
            'no_left_items' => 'required|boolean',
            'spareparts_returned' => 'required|boolean',
            'no_trash_left' => 'required|boolean',
            'access_closed' => 'required|boolean',
            'documentation_done' => 'required|boolean',
            'client_confirmed' => 'required|boolean',
            'client_name' => 'nullable|string|max:255',
            'closing_condition' => 'required|string',
            'signature' => 'nullable|string',
        ]);

        // server-side checks
        $errors = [];
        $afterPhotos = \App\Models\VisitPhoto::where('visit_id',$visit->id)->where('type','after')->count();
        $logs = \App\Models\VisitLog::where('visit_id',$visit->id)->count();
        $spareparts = \App\Models\VisitSparepart::where('visit_id',$visit->id)->count();

        if ($afterPhotos < 1) $errors[] = 'Foto kondisi sesudah belum diupload.';
        if ($logs < 1) $errors[] = 'Log pengerjaan belum diisi.';
        if (!$data['documentation_done']) $errors[] = 'Dokumentasi belum lengkap.';
        if (!$data['tools_collected']) $errors[] = 'Alat belum dikumpulkan kembali.';

        if (!$data['issue_resolved'] && empty($data['not_complete_reason'])) {
            $errors[] = 'Jika belum selesai, isi alasan dan langkah selanjutnya.';
        }
        if ($data['client_confirmed'] && empty($data['signature'])) {
            $errors[] = 'Tanda tangan klien/PIC diperlukan saat konfirmasi puas.';
        }

        if (!empty($errors)) {
            return back()->withErrors(['pre_pulang'=>$errors])->withInput();
        }

        // handle signature (base64 data URL) when provided
        $signaturePath = null;
        if (!empty($data['signature'])) {
            try {
                $b = $data['signature'];
                if (preg_match('/^data:image\/(png|jpeg);base64,/', $b, $m)) {
                    $b = preg_replace('/^data:image\/(png|jpeg);base64,/', '', $b);
                    $bin = base64_decode($b);
                    $dir = storage_path('app/public/visits/signatures'); if (!is_dir($dir)) mkdir($dir,0755,true);
                    $filename = 'visit_'.$visit->id.'_sig_'.time().'.png';
                    file_put_contents($dir.DIRECTORY_SEPARATOR.$filename, $bin);
                    $signaturePath = 'visits/signatures/'.$filename;
                }
            } catch (\Exception $e) {
                \Illuminate\Support\Facades\Log::error('Signature save failed: '.$e->getMessage());
            }
        }

        // save checklist
        $check = \App\Models\VisitChecklist::create([
            'visit_id'=>$visit->id,
            'user_id'=>auth()->id(),
            'data'=>$data,
            'completed'=>true,
            'completed_at'=>now(),
            'signature_path'=>$signaturePath,
        ]);

        // mark visit finished
        $visit->visit_time_end = now()->format('H:i:s');
        $visit->status = 'completed';
        $visit->save();

        // generate PDF report and notify via existing NotificationService
        try {
            $reportPath = app(\App\Services\VisitReportService::class)->generateAndStore($visit);
            // create CSAT survey for linked ticket (if any)
            if ($visit->ticket_id) {
                $ticket = $visit->ticket;
                $division = $ticket->division ?? 'JPN';
                $settings = \App\Models\CompanySetting::forDivision($division);
                
                $auto = $settings->csat_auto_send ?? true;
                $channelDefault = $settings->csat_default_channel ?? 'whatsapp';
                
                $payload = [
                    'ticket_id' => $visit->ticket_id,
                    'client_id' => $visit->client_id,
                    'token'     => \Illuminate\Support\Str::random(32),
                    'channel'   => $channelDefault,
                ];
                if ($auto) {
                    $payload['sent_at'] = now();
                }
                \App\Models\CsatSurvey::create($payload);
            }
            app(\App\Services\NotificationService::class)->notifyVisitCompleted($visit, $reportPath);
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error('Post-completion tasks error: '.$e->getMessage());
        }

        return redirect()->route('admin.visits.show',$visit)->with('success','Checklist Pre-Pulang lengkap. Kunjungan dapat ditutup.');
    }
}
