<?php

namespace App\Http\Controllers;

use App\Models\Complaint;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ComplaintController extends Controller
{
    /**
     * Show complaint form
     */

    public function showIzinPage()
    {
        $user = Auth::user();

        // Mapping saldo cuti
        $leaveBalance = [
            'annual'  => $user->annual_leave_quota ?? 0,
            'sick'    => $user->sick_leave_quota ?? 0,
            'special' => $user->special_leave_quota ?? 0,
        ];

        // Riwayat pengajuan user (opsional tapi sudah kamu pakai di blade)
        $complaints = $user->complaints()
            ->latest()
            ->take(5)
            ->get();

        return view('activities.izin', compact('leaveBalance', 'complaints'));
    }

    public function showForm()
    {
        return view('complaints.complaint-form');
    }

    /**
     * Store new complaint
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'title'       => 'required|string|max:255',
            'description' => 'required|string',
            'category'    => 'required|in:cuti,sakit,mendadak,keluarga,pribadi,lainnya', // PERBAIKAN DI SINI
            'priority'    => 'required|in:low,medium,high',
            'attachment'  => 'nullable|file|mimes:jpg,jpeg,png,pdf,doc,docx|max:5120',
            'admin_notes' => 'nullable|string',
            'start_date'  => 'required|date', // TAMBAHKAN
            'end_date'    => 'required|date|after_or_equal:start_date', // TAMBAHKAN
        ]);

        $data = [
            'user_id'    => auth()->id(),
            'title'      => $validated['title'],
            'description'=> $validated['description'],
            'category'   => $validated['category'],
            'priority'   => $validated['priority'],
            'status'     => 'pending',
            'notes'      => $validated['admin_notes'] ?? null,
            'start_date' => $validated['start_date'], // TAMBAHKAN
            'end_date'   => $validated['end_date'],   // TAMBAHKAN
        ];

        if ($request->hasFile('attachment')) {
            $data['attachment'] = $request->file('attachment')
                ->store('complaints', 'public');
        }

        Complaint::create($data);

        return redirect()
            ->back()
            ->with('success', 'Pengajuan izin berhasil dikirim');
    }


   public function storeComplaint(Request $request)
    {
        \Log::info($request->all());
        $validated = $request->validate([
            'category'          => 'required|string',
            'title'             => 'required|string|max:100',
            'description'       => 'required|string|min:20|max:1000',
            'priority'          => 'required|in:low,medium,high',
            'incident_date'     => 'nullable|date',
            'email'             => 'nullable|email',

            // FOTO SEBELUM
            'attachment'        => 'nullable|image|max:5120',

            // FOTO SESUDAH
            'attachment_after'  => 'nullable|image|max:5120',
        ]);

        $attachmentBefore = null;
        $attachmentAfter  = null;

        // simpan foto sebelum
        if ($request->hasFile('attachment')) {
            $attachmentBefore = $request->file('attachment')
                ->store('complaints/before', 'public');
        }

        // simpan foto sesudah
        if ($request->hasFile('attachment_after')) {
            $attachmentAfter = $request->file('attachment_after')
                ->store('complaints/after', 'public');
        }

        $complaint = Complaint::create([
            'user_id'          => Auth::id(),
            'category'         => $validated['category'],
            'title'            => $validated['title'],
            'description'      => $validated['description'],
            'priority'         => $validated['priority'],
            'status'           => 'pending',

            'incident_date'    => $validated['incident_date'] ?? null,
            'email'            => $validated['email'] ?? null,

            // attachment
            'attachment'       => $attachmentBefore,
            'attachment_after' => $attachmentAfter,
        ]);

        return response()->json([
            'success' => true,
            'ticket'  => 'CMP-' . str_pad($complaint->id, 6, '0', STR_PAD_LEFT),
        ]);
    }


    /**
     * Show user's complaint history
     */
    public function history(Request $request)
    {
        $userId = Auth::id();
        
        // Get statistics
        $stats = [
            'pending' => Complaint::where('user_id', $userId)
                ->where('status', 'pending')->count(),
            'process' => Complaint::where('user_id', $userId)
                ->where('status', 'in_progress')->count(),
            'done' => Complaint::where('user_id', $userId)
                ->where('status', 'resolved')->count(),
        ];

        // Get complaints with optional filtering
        $status = $request->get('status', 'all');
        
        $query = Complaint::where('user_id', $userId)
            ->orderBy('created_at', 'desc');

        if ($status !== 'all') {
            $query->where('status', $this->mapStatus($status));
        }

        $complaints = $query->paginate(10);

        // Format complaints data for view
        $formattedComplaints = $complaints->map(function ($complaint) {
            return [
                'id' => $complaint->id,
                'ticketNumber' => 'TICKET-' . str_pad($complaint->id, 6, '0', STR_PAD_LEFT),
                'title' => $complaint->title,
                'description' => $complaint->description,
                'category' => $complaint->category,
                'priority' => $complaint->priority,
                'status' => $this->mapStatusToSimple($complaint->status),
                'createdAt' => $complaint->created_at->toDateTimeString(),
                'attachment' => $complaint->attachment,
                'response' => $complaint->response,
                'responded_at' => $complaint->responded_at,
                'location' => $complaint->location,
                'notes' => $complaint->notes,
                'technician' => $complaint->responder ? $complaint->responder->name : null,
            ];
        });

        return view('complaints.complaint-history', [
            'complaints' => $formattedComplaints,
            'stats' => $stats,
            'currentStatus' => $status,
            'pagination' => $complaints,
        ]);
    }

    /**
     * Show complaint detail
     */
    public function show($id)
    {
        $complaint = Complaint::with('responder')
            ->where('user_id', Auth::id())
            ->findOrFail($id);

        $formattedComplaint = [
            'id' => $complaint->id,
            'ticketNumber' => 'TICKET-' . str_pad($complaint->id, 6, '0', STR_PAD_LEFT),
            'title' => $complaint->title,
            'description' => $complaint->description,
            'category' => $complaint->category,
            'priority' => $complaint->priority,
            'status' => $this->mapStatusToSimple($complaint->status),
            'createdAt' => $complaint->created_at->toDateTimeString(),
            'attachment' => $complaint->attachment,
            'response' => $complaint->response,
            'responded_at' => $complaint->responded_at,
            'location' => $complaint->location,
            'notes' => $complaint->notes,
            'technician' => $complaint->responder ? $complaint->responder->name : null,
        ];

        return view('complaints.complaint-detail', [
            'complaint' => $formattedComplaint,
        ]);
    }

    /**
     * Map simple status to database status
     */
    private function mapStatus($simpleStatus)
    {
        $map = [
            'pending' => 'pending',
            'process' => 'in_progress',
            'done' => 'resolved',
        ];
        
        return $map[$simpleStatus] ?? $simpleStatus;
    }

    /**
     * Map database status to simple status
     */
    private function mapStatusToSimple($dbStatus)
    {
        $map = [
            'pending' => 'pending',
            'in_progress' => 'process',
            'resolved' => 'done',
            'closed' => 'done',
        ];
        
        return $map[$dbStatus] ?? $dbStatus;
    }

    /**
     * Get status text in Indonesian
     */
    private function getStatusText($status)
    {
        $map = [
            'pending' => 'Menunggu',
            'process' => 'Diproses',
            'in_progress' => 'Diproses',
            'done' => 'Selesai',
            'resolved' => 'Selesai',
            'closed' => 'Selesai',
        ];
        
        return $map[$status] ?? $status;
    }

    /**
     * Get category text in Indonesian
     */
    private function getCategoryText($category)
    {
        $map = [
            'hardware' => 'Hardware/Perangkat',
            'software' => 'Software/Aplikasi',
            'network' => 'Jaringan/Internet',
            'system' => 'Sistem Absensi',
            'access' => 'Akses/Login',
            'general' => 'Umum',
            'other' => 'Lainnya',
        ];
        
        return $map[$category] ?? $category;
    }

    /**
     * Get priority text in Indonesian
     */
    private function getPriorityText($priority)
    {
        $map = [
            'low' => 'Rendah',
            'medium' => 'Sedang',
            'high' => 'Tinggi',
        ];
        
        return $map[$priority] ?? $priority;
    }

    /**
     * Format date
     */
    private function formatDate($dateString)
    {
        return \Carbon\Carbon::parse($dateString)
            ->locale('id_ID')
            ->translatedFormat('d M Y');
    }

    /**
     * Format date time
     */
    private function formatDateTime($dateString)
    {
        return \Carbon\Carbon::parse($dateString)
            ->locale('id_ID')
            ->translatedFormat('d M Y, H:i');
    }
}