<?php

namespace App\Http\Controllers\Api;

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

class PublicVisitController extends Controller
{
    /**
     * View visit details with token validation
     */
    public function show(Request $request, int $id)
    {
        $token = $request->query('token');

        if (!$token) {
            return response()->json([
                'message' => 'Token is required'
            ], 401);
        }

        $visit = Visit::findOrFail($id);

        // Validate token
        $expectedToken = hash('sha256', $visit->id . $visit->created_at . config('app.key'));

        if ($token !== $expectedToken) {
            return response()->json([
                'message' => 'Invalid token'
            ], 401);
        }

        // Return visit details (similar format to the authenticated endpoint)
        return response()->json($this->transformVisitForPublic($visit));
    }

    /**
     * Transform visit for public viewing
     */
    private function transformVisitForPublic(Visit $visit): array
    {
        // Transform main visitor
        $mainVisitor = [
            'id' => $visit->mainVisitor?->id ? (string)$visit->mainVisitor->id : null,
            'name' => $visit->mainVisitor?->name ?? null,
            'email' => $visit->main_visitor_email,
            'phone' => $visit->mainVisitor?->phone ?? null,
            'companyName' => $visit->mainVisitor?->company_name ?? null,
            'idFrontImage' => $visit->mainVisitor?->id_front_image_url ?? null,
            'idBackImage' => $visit->mainVisitor?->id_back_image_url ?? null,
        ];

        // Transform additional visitors
        $additionalVisitors = $visit->additionalVisitors->map(function ($visitor) {
            return [
                'id' => (string)$visitor->id,
                'name' => $visitor->name,
                'email' => $visitor->email,
                'phone' => $visitor->phone,
                'companyName' => $visitor->company_name ?? null,
                'idFrontImage' => $visitor->id_front_image_url ?? null,
                'idBackImage' => $visitor->id_back_image_url ?? null,
            ];
        })->toArray();

        // Convert times from 24-hour to 12-hour AM/PM format
        $startTime = $this->formatTimeTo12Hour($visit->start_time);
        $endTime = $this->formatTimeTo12Hour($visit->end_time);

        // Build response
        $response = [
            'id' => (string)$visit->id,
            'requestId' => $visit->request_id,
            'hostVisitor' => [
                'name' => $visit->host_name,
                'email' => $visit->host_email,
                'phone' => $visit->host_phone,
                'location' => $visit->location?->name ?? '',
            ],
            'mainVisitor' => $mainVisitor,
            'additionalVisitors' => $additionalVisitors,
            'visitReason' => $visit->visit_reason,
            'meetingType' => $visit->meeting_type,
            'status' => $visit->status,
        ];

        // Add date fields based on meeting type
        if ($visit->meeting_type === 'single' && $visit->date) {
            $response['date'] = $visit->date->format('Y-m-d');
        } else {
            $response['dateFrom'] = $visit->date_from?->format('Y-m-d');
            $response['dateTo'] = $visit->date_to?->format('Y-m-d');
        }

        // Add times
        $response['startTime'] = $startTime;
        $response['endTime'] = $endTime;

        // Add rejection reason if status is rejected
        if ($visit->status === 'Rejected') {
            $response['rejectionReason'] = $visit->rejection_reason;
        }

        return $response;
    }

    /**
     * Convert 24-hour time to 12-hour AM/PM format
     */
    private function formatTimeTo12Hour(string $time): string
    {
        // Parse time (HH:MM:SS format)
        $parts = explode(':', $time);
        $hour = (int)$parts[0];
        $minute = $parts[1];

        // Convert to 12-hour format
        $amPm = $hour >= 12 ? 'PM' : 'AM';
        $hour12 = $hour % 12;
        if ($hour12 === 0) {
            $hour12 = 12;
        }

        return sprintf('%d:%s %s', $hour12, $minute, $amPm);
    }
}
