<?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 showForm()
    {
        return view('complaints.complaint-form');
    }

    /**
     * Store new complaint
     */
    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'category' => 'required|string',
            'priority' => 'required|in:low,medium,high',
            'attachment' => 'nullable|image|max:5120',
        ]);

        $data = [
            'user_id' => Auth::id(),
            'title' => $request->title,
            'description' => $request->description,
            'category' => $request->category,
            'priority' => $request->priority,
            'status' => 'pending',
        ];

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

        Complaint::create($data);

        return redirect()
            ->route('complaints.history')
            ->with('success', 'Keluhan berhasil dikirim');
    }

    /**
     * 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');
    }
}