<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Tuupola\Base62;
use App\Models\Website\SiteUrlShortenerMapping;

class UrlController extends Controller
{
    protected $base62;

    public function __construct()
    {
        $this->base62 = new Base62();
    }

    public function shorten(Request $request)
    {
        // Extract the booking number from the original URL
        $originalUrl = $request->input('url');
        $urlParts = parse_url($originalUrl);
        parse_str($urlParts['query'], $queryParams);

        $actionType = 'internal';
        
        if (config('app.url') !==  $urlParts['scheme'] . '://' . $urlParts['host']) {
            $actionType = 'external';
        }

        $queryString = http_build_query($queryParams);
        // Encrypt the booking number
        $encryptedQueryString = Crypt::encryptString($queryString);

        // Encode the encrypted string to base62 and take the first 6 characters
        $shortCode = substr($this->base62->encode($encryptedQueryString), 12, 6);
        //dd($encryptedQueryString, $shortCode, $this->base62->encode($encryptedQueryString));

        //dd($queryParams, $urlParts, $queryParams['booking_id'], $shortCode, $encryptedBookingId);
        //dd($queryString);
        $urlShortener = SiteUrlShortenerMapping::firstOrNew(
            ['url' => $originalUrl],
            [
                'short_code' => $shortCode,
                'action_type' => $actionType,
                'encoded_string' => $encryptedQueryString,
                'route' => $urlParts['path'],
                'query_param' => $queryString ?? '',  // Provide a default value here
            ]
        );

        if (!$urlShortener->exists) {
            $urlShortener->save();
        }

        // Generate the shortened URL
        $shortenedUrl = $urlParts['scheme'] . '://' . $urlParts['host'] . $urlParts['path'] . '/' . $urlShortener->short_code;

        if ($urlShortener->action_type == 'internal') {
            return response()->json(['shortened_url' => $shortenedUrl]);
        }elseif($urlShortener->action_type == 'external'){
            return response()->json(['short_code' => $urlShortener->short_code, 'full_url' => $urlShortener->url]);
        }
    }

    public function shortenUrl($url)
    {
        // Extract the booking number from the original URL
        $originalUrl = $url;
        $urlParts = parse_url($originalUrl);
        parse_str($urlParts['query'], $queryParams);

        $actionType = 'internal';
        
        if (config('app.url') !==  $urlParts['scheme'] . '://' . $urlParts['host']) {
            $actionType = 'external';
        }
        //dd($urlParts, $actionType, config('app.url') !==  $urlParts['scheme'] . '://' . $urlParts['host'], config('app.url'), $urlParts['scheme'] . '://' . $urlParts['host']);
        $queryString = http_build_query($queryParams);
        // Encrypt the booking number
        $encryptedQueryString = Crypt::encryptString($queryString);

        // Encode the encrypted string to base62 and take the first 6 characters
        $shortCode = substr($this->base62->encode($encryptedQueryString), 12, 6);
        //dd($encryptedQueryString, $shortCode, $this->base62->encode($encryptedQueryString));

        //dd($queryParams, $urlParts, $queryParams['booking_id'], $shortCode, $encryptedBookingId);
        //dd($queryString);
        $urlShortener = SiteUrlShortenerMapping::firstOrNew(
            ['url' => $originalUrl],
            [
                'short_code' => $shortCode,
                'action_type' => $actionType,
                'encoded_string' => $encryptedQueryString,
                'route' => $urlParts['path'],
                'query_param' => $queryString ?? '',  // Provide a default value here
            ]
        );

        if (!$urlShortener->exists) {
            $urlShortener->save();
        }
        
        // Generate the shortened URL
        $shortenedUrl = $urlParts['scheme'] . '://' . $urlParts['host'] . $urlParts['path'] . '/' . $urlShortener->short_code;

        if ($urlShortener->action_type == 'internal') {
            return ['short_code' => $urlShortener->short_code, 'shortened_url' => $shortenedUrl];
        }elseif($urlShortener->action_type == 'external'){
            return ['short_code' => $urlShortener->short_code, 'full_url' => $urlShortener->url];
        }
    }

    public function shortenSlugUrl($url, $slug, $slugType, $originalUrl = '', $originalSlug = '')
    {
        // Extract the booking number from the original URL
        $initialUrl = $url;
        $urlParts = parse_url($initialUrl);
        //parse_str($urlParts['query'], $queryParams);
        //dd($urlParts);
        $actionType = 'slug.'.$slugType;
        //dd($actionType);
        // if (config('app.url') !==  $urlParts['scheme'] . '://' . $urlParts['host']) {
        //     $actionType = 'external';
        // }
        //dd($urlParts, $actionType, config('app.url') !==  $urlParts['scheme'] . '://' . $urlParts['host'], config('app.url'), $urlParts['scheme'] . '://' . $urlParts['host']);
        //$queryString = http_build_query($queryParams);
        // Encrypt the booking number
        //$encryptedQueryString = Crypt::encryptString($queryString);

        // Encode the encrypted string to base62 and take the first 6 characters
        $shortCode = $slug;
        //dd($actionType, $shortCode);
        //dd($encryptedQueryString, $shortCode, $this->base62->encode($encryptedQueryString));

        //dd($queryParams, $urlParts, $queryParams['booking_id'], $shortCode, $encryptedBookingId);
        //dd($queryString);
        // dd($originalSlug);
        if ($originalUrl && $originalSlug) {
            // dd($originalUrl);
            $urlShortener = SiteUrlShortenerMapping::where('url', $originalUrl)
                ->where('short_code', $originalSlug)
                ->first();
            // dd($urlShortener);
        
            if ($urlShortener) {
                $urlShortener->url = $initialUrl;
                $urlShortener->short_code = $slug;
                $urlShortener->save();
            } else {
                return response()->json(['error' => 'Record not found'], 404);
            }
        } else {
            // Create or find a new record
            $urlShortener = SiteUrlShortenerMapping::firstOrNew(
                ['url' => $initialUrl],
                [
                    'action_type' => $actionType,
                    'encoded_string' => '-',
                    'route' => $urlParts['path'],
                    'query_param' => $queryString ?? '',  // Provide a default value here
                ]
            );
        }

        if ($urlShortener->exists) {
            
            // If the short_code is different, ensure uniqueness before updating
            if ($urlShortener->short_code !== $shortCode) {
                $isShortCodeUnique = !SiteUrlShortenerMapping::where('short_code', $shortCode)
                    ->where('id', '!=', $urlShortener->id) // Exclude current record
                    ->exists();
        
                if (!$isShortCodeUnique) {
                    return response()->json(['error' => 'Short code already exists'], 400);
                }
        
                $urlShortener->short_code = $shortCode;
            }
        } else {
            // For a new record, directly set the short_code
            $urlShortener->short_code = $shortCode;
        }

        $urlShortener->save();
        
        // Generate the shortened URL
        $shortenedUrl = $urlParts['scheme'] . '://' . $urlParts['host'] . $urlParts['path'] . '/' . $urlShortener->short_code;

        if ($urlShortener->action_type == 'internal') {
            return ['short_code' => $urlShortener->short_code, 'shortened_url' => $shortenedUrl];
        }elseif($urlShortener->action_type == 'external'){
            return ['short_code' => $urlShortener->short_code, 'full_url' => $urlShortener->url];
        }else{
            return ['short_code' => $urlShortener->short_code, 'full_url' => $urlShortener->url];
        }
    }

    public function removeShortenSlugUrl($shortCode){
        SiteUrlShortenerMapping::where('short_code', $shortCode)->delete();
    }

    public function decrypt($encrypted)
    {
        // Decrypt the booking number
        $decryptedBookingNumber = Crypt::decryptString($encrypted);

        return response()->json(['booking_number' => $decryptedBookingNumber]);
    }
}
