<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Helpers\DateHelper;
use Carbon\Carbon;

class DateController extends Controller
{
    /**
     * Convert date between different formats and locales
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function convertDate(Request $request)
    {
        $request->validate([
            'date' => 'required',
            'type' => 'required|in:jalali,gregorian,format,relative',
            'locale' => 'sometimes|string',
            'format' => 'sometimes|string'
        ]);

        try {
            $date = $request->input('date');
            $type = $request->input('type');
            $locale = $request->input('locale', app()->getLocale());
            $format = $request->input('format', 'Y/m/d');

            // Convert string date to Carbon instance
            if (!$date instanceof Carbon) {
                $date = Carbon::parse($date);
            }

            $convertedDate = '';

            switch ($type) {
                case 'jalali':
                    $convertedDate = DateHelper::toPersian($date, $format);
                    break;

                case 'gregorian':
                    $convertedDate = DateHelper::toGregorian($date, $format);
                    break;

                case 'format':
                    $convertedDate = DateHelper::formatByLocale($date, $format, $locale);
                    break;

                case 'relative':
                    $convertedDate = DateHelper::formatRelativeByLocale($date, $locale);
                    break;

                default:
                    $convertedDate = DateHelper::formatByLocale($date, $format, $locale);
            }

            return response()->json([
                'success' => true,
                'converted_date' => $convertedDate,
                'original_date' => $request->input('date'),
                'type' => $type,
                'locale' => $locale
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => 'تبدیل تاریخ با خطا مواجه شد',
                'message' => $e->getMessage()
            ], 400);
        }
    }

    /**
     * Get formatted date for charts
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function formatForChart(Request $request)
    {
        $request->validate([
            'dates' => 'required|array',
            'locale' => 'sometimes|string',
            'format' => 'sometimes|string'
        ]);

        try {
            $dates = $request->input('dates');
            $locale = $request->input('locale', app()->getLocale());
            $format = $request->input('format', 'Y/m/d');

            $formattedDates = [];

            foreach ($dates as $date) {
                $carbonDate = Carbon::parse($date);
                $formattedDates[] = [
                    'original' => $date,
                    'formatted' => DateHelper::formatByLocale($carbonDate, $format, $locale),
                    'timestamp' => $carbonDate->timestamp
                ];
            }

            return response()->json([
                'success' => true,
                'formatted_dates' => $formattedDates,
                'locale' => $locale
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => 'فرمت کردن تاریخ‌ها با خطا مواجه شد',
                'message' => $e->getMessage()
            ], 400);
        }
    }

    /**
     * Get month names for charts
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMonthNames(Request $request)
    {
        $locale = $request->input('locale', app()->getLocale());

        if ($locale === 'fa') {
            $months = [
                1 => 'فروردین', 2 => 'اردیبهشت', 3 => 'خرداد',
                4 => 'تیر', 5 => 'مرداد', 6 => 'شهریور',
                7 => 'مهر', 8 => 'آبان', 9 => 'آذر',
                10 => 'دی', 11 => 'بهمن', 12 => 'اسفند'
            ];
        } else {
            $months = [];
            for ($i = 1; $i <= 12; $i++) {
                $date = Carbon::create(2000, $i, 1);
                $months[$i] = $date->format('F');
            }
        }

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

    /**
     * Get day names for charts
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getDayNames(Request $request)
    {
        $locale = $request->input('locale', app()->getLocale());

        if ($locale === 'fa') {
            $days = [
                0 => 'شنبه', 1 => 'یکشنبه', 2 => 'دوشنبه',
                3 => 'سه‌شنبه', 4 => 'چهارشنبه', 5 => 'پنج‌شنبه', 6 => 'جمعه'
            ];
            $daysShort = [
                0 => 'ش', 1 => 'ی', 2 => 'د',
                3 => 'س', 4 => 'چ', 5 => 'پ', 6 => 'ج'
            ];
        } else {
            $days = [
                0 => 'Sunday', 1 => 'Monday', 2 => 'Tuesday',
                3 => 'Wednesday', 4 => 'Thursday', 5 => 'Friday', 6 => 'Saturday'
            ];
            $daysShort = [
                0 => 'Sun', 1 => 'Mon', 2 => 'Tue',
                3 => 'Wed', 4 => 'Thu', 5 => 'Fri', 6 => 'Sat'
            ];
        }

        return response()->json([
            'success' => true,
            'days' => $days,
            'days_short' => $daysShort,
            'locale' => $locale
        ]);
    }

    /**
     * Convert numbers to Persian or English
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function convertNumbers(Request $request)
    {
        $request->validate([
            'numbers' => 'required',
            'to' => 'required|in:persian,english'
        ]);

        try {
            $numbers = $request->input('numbers');
            $to = $request->input('to');

            if ($to === 'persian') {
                $converted = DateHelper::convertToPersianNumbers($numbers);
            } else {
                $converted = DateHelper::convertToEnglishNumbers($numbers);
            }

            return response()->json([
                'success' => true,
                'converted_numbers' => $converted,
                'original_numbers' => $numbers,
                'to' => $to
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => 'تبدیل اعداد با خطا مواجه شد',
                'message' => $e->getMessage()
            ], 400);
        }
    }
}
