<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Document;
use App\Models\BusinessTrip;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;

class DocumentController extends Controller
{
    /**
     * Get all documents for authenticated user
     */
    public function index(Request $request)
    {
        $user = $request->user();

        $documents = Document::where('user_id', $user->id)
            ->with(['businessTrip:id,title', 'approver:id,name'])
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($doc) {
                return [
                    'id' => $doc->id,
                    'business_trip_id' => $doc->business_trip_id,
                    'business_trip_title' => $doc->businessTrip?->title,
                    'type' => $doc->type,
                    'type_label' => $doc->type_label,
                    'file_name' => $doc->file_name,
                    'file_size' => $doc->file_size,
                    'file_size_formatted' => $doc->file_size_formatted,
                    'description' => $doc->description,
                    'status' => $doc->status,
                    'rejection_reason' => $doc->rejection_reason,
                    'approved_by' => $doc->approver?->name,
                    'approved_at' => $doc->approved_at?->format('Y-m-d H:i:s'),
                    'hardcopy_received' => $doc->hardcopy_received,
                    'created_at' => $doc->created_at->format('Y-m-d H:i:s'),
                ];
            });

        return response()->json([
            'success' => true,
            'data' => $documents,
        ]);
    }

    /**
     * Get documents for specific business trip
     */
    public function byBusinessTrip(Request $request, BusinessTrip $businessTrip)
    {
        $user = $request->user();

        // Check if user owns this business trip
        if ($businessTrip->user_id !== $user->id) {
            return response()->json([
                'success' => false,
                'message' => 'Anda tidak memiliki akses ke perjalanan dinas ini',
            ], 403);
        }

        $documents = Document::where('business_trip_id', $businessTrip->id)
            ->with(['approver:id,name'])
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($doc) {
                return [
                    'id' => $doc->id,
                    'type' => $doc->type,
                    'type_label' => $doc->type_label,
                    'file_name' => $doc->file_name,
                    'file_url' => Storage::url($doc->file_path),
                    'file_size_formatted' => $doc->file_size_formatted,
                    'description' => $doc->description,
                    'status' => $doc->status,
                    'rejection_reason' => $doc->rejection_reason,
                    'approved_by' => $doc->approver?->name,
                    'approved_at' => $doc->approved_at?->format('Y-m-d H:i:s'),
                    'hardcopy_received' => $doc->hardcopy_received,
                    'created_at' => $doc->created_at->format('Y-m-d H:i:s'),
                ];
            });

        return response()->json([
            'success' => true,
            'data' => $documents,
        ]);
    }

    /**
     * Upload new document
     */
    public function store(Request $request)
    {
        $user = $request->user();

        // Check if company allows document upload
        if (!$user->company->allow_document_upload) {
            return response()->json([
                'success' => false,
                'message' => 'Fitur upload dokumen tidak aktif untuk perusahaan Anda',
            ], 403);
        }

        $validated = $request->validate([
            'business_trip_id' => ['nullable', 'exists:business_trips,id'],
            'type' => ['required', Rule::in([
                'tiket_pesawat',
                'tiket_kereta',
                'tiket_bus',
                'boarding_pass',
                'hotel_invoice',
                'kwitansi_bbm',
                'toll_receipt',
                'surat_tugas',
                'lainnya',
            ])],
            'file' => ['required', 'file', 'mimes:pdf,jpg,jpeg,png', 'max:5120'],
            'description' => ['nullable', 'string', 'max:500'],
        ]);

        // Validate business trip ownership if provided
        if ($validated['business_trip_id']) {
            $businessTrip = BusinessTrip::find($validated['business_trip_id']);
            if ($businessTrip->user_id !== $user->id) {
                return response()->json([
                    'success' => false,
                    'message' => 'Anda tidak memiliki akses ke perjalanan dinas ini',
                ], 403);
            }
        }

        // Store file
        $file = $request->file('file');
        $fileName = time() . '_' . $file->getClientOriginalName();
        $filePath = $file->storeAs('documents', $fileName, 'public');

        $document = Document::create([
            'business_trip_id' => $validated['business_trip_id'] ?? null,
            'user_id' => $user->id,
            'type' => $validated['type'],
            'file_name' => $file->getClientOriginalName(),
            'file_path' => $filePath,
            'file_type' => $file->getMimeType(),
            'file_size' => $file->getSize(),
            'description' => $validated['description'] ?? null,
            'status' => 'pending',
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Dokumen berhasil diupload',
            'data' => [
                'id' => $document->id,
                'type' => $document->type,
                'type_label' => $document->type_label,
                'file_name' => $document->file_name,
                'file_size_formatted' => $document->file_size_formatted,
                'status' => $document->status,
                'created_at' => $document->created_at->format('Y-m-d H:i:s'),
            ],
        ], 201);
    }

    /**
     * Get document detail
     */
    public function show(Request $request, Document $document)
    {
        $user = $request->user();

        // Check ownership
        if ($document->user_id !== $user->id) {
            return response()->json([
                'success' => false,
                'message' => 'Anda tidak memiliki akses ke dokumen ini',
            ], 403);
        }

        return response()->json([
            'success' => true,
            'data' => [
                'id' => $document->id,
                'business_trip_id' => $document->business_trip_id,
                'business_trip_title' => $document->businessTrip?->title,
                'type' => $document->type,
                'type_label' => $document->type_label,
                'file_name' => $document->file_name,
                'file_url' => Storage::url($document->file_path),
                'file_type' => $document->file_type,
                'file_size' => $document->file_size,
                'file_size_formatted' => $document->file_size_formatted,
                'description' => $document->description,
                'status' => $document->status,
                'rejection_reason' => $document->rejection_reason,
                'approved_by' => $document->approver?->name,
                'approved_at' => $document->approved_at?->format('Y-m-d H:i:s'),
                'hardcopy_received' => $document->hardcopy_received,
                'hardcopy_received_at' => $document->hardcopy_received_at?->format('Y-m-d H:i:s'),
                'created_at' => $document->created_at->format('Y-m-d H:i:s'),
            ],
        ]);
    }

    /**
     * Delete document (only if pending)
     */
    public function destroy(Request $request, Document $document)
    {
        $user = $request->user();

        // Check ownership
        if ($document->user_id !== $user->id) {
            return response()->json([
                'success' => false,
                'message' => 'Anda tidak memiliki akses ke dokumen ini',
            ], 403);
        }

        // Can only delete pending documents
        if ($document->status !== 'pending') {
            return response()->json([
                'success' => false,
                'message' => 'Hanya dokumen dengan status pending yang dapat dihapus',
            ], 422);
        }

        // Delete file
        Storage::disk('public')->delete($document->file_path);

        $document->delete();

        return response()->json([
            'success' => true,
            'message' => 'Dokumen berhasil dihapus',
        ]);
    }

    /**
     * Get document types
     */
    public function types()
    {
        return response()->json([
            'success' => true,
            'data' => [
                ['value' => 'tiket_pesawat', 'label' => 'Tiket Pesawat'],
                ['value' => 'tiket_kereta', 'label' => 'Tiket Kereta'],
                ['value' => 'tiket_bus', 'label' => 'Tiket Bus'],
                ['value' => 'boarding_pass', 'label' => 'Boarding Pass'],
                ['value' => 'hotel_invoice', 'label' => 'Invoice Hotel'],
                ['value' => 'kwitansi_bbm', 'label' => 'Kwitansi BBM'],
                ['value' => 'toll_receipt', 'label' => 'Bukti Tol'],
                ['value' => 'surat_tugas', 'label' => 'Surat Tugas'],
                ['value' => 'lainnya', 'label' => 'Lainnya'],
            ],
        ]);
    }
}
