<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Link;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use GuzzleHttp\Client;

class LinkController extends Controller
{
    public function index()
    {
        $page = 'Shortlinks';
        return view('admin.links', compact('page'));
    }
    public function advertise(Request $request)
    {
        $page = 'Shortlink Ads';

        return view('admin.advertiser.link', compact(
            'page'
        ));
    }
    public function load()
    {
        $links = Link::where('user_id', 0)->get();
        return response()->json($links);
    }
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'api_url' => 'required|url',
            'reward' => 'required|numeric|min:0',
            'limit' => 'required|numeric|min:1'
        ]);
    
        $data = $request->all();
        $data['countries'] = '*';
    
        Link::create($data);
    
        return response()->json(['message' => 'Link added successfully!']);
    }

    public function edit($id)
    {
        return response()->json(Link::findOrFail($id));
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'api_url' => 'required|url',
            'reward' => 'required|numeric|min:0',
            'limit' => 'required|numeric|min:1',
        ]);

        Link::findOrFail($id)->update($request->all());

        return response()->json(['message' => 'Link updated successfully!']);
    }

    public function destroy($id)
    {
        Link::findOrFail($id)->delete();

        return response()->json(['message' => 'Link deleted successfully!']);
    }
    public function fetchAds(Request $request, $status)
    {
        if (!$request->ajax()) {
            return response()->json(['error' => 'Invalid request'], 400);
        }
        $perPage = 10;

        $Ads = Link::with('user') 
            ->orderBy('created_at', 'desc')
            ->where('status', $status)
            ->where('user_id', '!=', 0)
            ->paginate($perPage);
            
        $records = $Ads->map(function ($item) {
            return [
                'id' => $item->id,
                'user_id' => $item->user_id,
                'username' => optional($item->user)->name,
                'name' => $item->name,
                'url' => $item->api_url,
                'remaining_views' => $item->remaining_views,
                'today_views' => $item->today_views,
                'views' => $item->views,
                'status' => $item->status,
            ];
        });
        
        return response()->json([
            'records' => $records,
            'current_page' => $Ads->currentPage(),
            'total_pages' => $Ads->lastPage(),
            'prev_page' => $Ads->previousPageUrl() ? $Ads->currentPage() - 1 : null,
            'next_page' => $Ads->nextPageUrl() ? $Ads->currentPage() + 1 : null,
        ]);
    }
    public function updateStatus(Request $request)
    {
        $request->validate([
            'status' => 'required|integer|in:1,2',
            'id' => 'required|integer',
        ]);
        $id = $request->id;
        $ad = Link::findOrFail($id);
        $owner = User::findOrFail($ad->user_id);
        if ($request->status == 2) {
            $fee = get_setting('link_fee');
            $refundAmount = $ad->remaining_views * $ad->reward;
            
            $feeAmount = ($refundAmount * $fee) / 100;
            $refundAmount += $feeAmount;
            
            $owner->available_deposit += $refundAmount;
            $owner->save();
            create_notification('Ad Rejected', "Your Shortlink ad #{$ad->id} was rejected. Refund: $".formatUSD($refundAmount).".", 'warning', $owner->id);
        }else{
            create_notification('Ad Approved', "Your Shortlink ad #{$ad->id} has been approved.", 'success', $owner->id);
        }
    
        $ad->status = $request->status;
        $ad->save();
    
        return response()->json(['message' => 'Status updated successfully!']);
    }
    public function storeLink(Request $request)
    {
        try {
            $validated = $request->validate([
                'name' => 'required|string|max:100',
                'url' => 'required|url',
                'countries' => 'nullable|array',
                'reward' => 'required|numeric|min:0',
                'views' => 'required|numeric|min:1',
                'limit_per_day' => 'required|integer|min:1',
                'select_all' => 'nullable|integer|in:0,1',
            ]);
            
            $countries = $request->select_all == 1 ? '*' : (is_array($request->countries) ? implode(',', $request->countries) : '*');
            
            $user = auth()->user();
            $link_min_reward = get_setting('link_min_reward')/get_setting('currency_rate');
            $link_minimum_limit = get_setting('link_minimum_limit');
            $fee = get_setting('link_fee');
            
            if ($validated['reward'] < $link_min_reward) {
                return redirect('/admin/advertise/link')->with('message', "Minimum Reward is ".balanceAndSymbol($link_min_reward))->with('type', 'error');
            }
            
            if ($validated['views'] < $link_minimum_limit) {
                return redirect('/admin/advertise/link')->with('message', "Minimum views required: $link_minimum_limit.")->with('type', 'error');
            }
            
            if ($validated['limit_per_day'] > $validated['views']) {
                return redirect('/admin/advertise/link')->with('message', 'Daily limit cannot exceed total views.')->with('type', 'error');
            }
            
            $reward = $validated['reward'] / get_setting('currency_rate');

            $client = new Client();
            
            $token = Str::random(33);
            $backUrl = url('/link/back/'.$token);
            
            try {
                $response = $client->get($validated['url'].$backUrl);
            
                $result = json_decode($response->getBody(), true);
            
                if (!isset($result["status"])) {
                    throw new \Exception('Failed to shorten URL: Invalid Api URL');
                }
            
                if ($result["status"] === 'error') {
                    return redirect()->back()->with('message', $result["message"])->with('type', 'error');
                } 
            } catch (\Exception $e) {
                return redirect()->back()->with('message', $e->getMessage())->with('type', 'error');
            }
            
            Link::create([
                'user_id' => Auth::id(),
                'name' => $validated['name'],
                'api_url' => $validated['url'],
                'countries' => $countries,
                'remaining_views' => $validated['views'],
                'reward' => $reward,
                'limit' => $validated['limit_per_day'],
                'status' => 1,
            ]);
    
            return redirect()->back()->with('message', 'Ad created successfully!')->with('type', 'success');
        } catch (\Illuminate\Validation\ValidationException $e) {
            $errorMessages = implode(', ', $e->validator->errors()->all());
    
            return redirect()->back()
                ->withErrors($e->validator)
                ->with('message', 'Validation failed! Errors: ' . $errorMessages)
                ->with('type', 'danger');
        }
    }
}