<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use App\Models\Ptc;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Carbon\Carbon;

class PtcController extends Controller
{
    public function index(Request $request)
    {
        $page = 'PTC Ads';

        return view('admin.advertiser.ptc', compact(
            'page'
        ));
    }

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

        $Ads = Ptc::with('user') 
            ->orderBy('created_at', 'desc')
            ->where('status', $status)
            ->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->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 store(Request $request)
    {
        try {
            $validated = $request->validate([
                'name' => 'required|string|max:100',
                'description' => 'required|string|max:255',
                'url' => 'required|url',
                'countries' => 'nullable|array',
                'views' => 'required|numeric|min:1',
                'timer' => 'required|integer|min:5',
                'limit_per_day' => 'nullable|integer|min:1',
                'type' => 'required|integer|in:0,1',
                'select_all' => 'nullable|integer|in:0,1',
            ]);
            
            $countries = $request->select_all == 1 ? '*' : (is_array($request->countries) ? implode(',', $request->countries) : '*');
            
            $user = auth()->user();
            $ptc_min_timer = get_setting('ptc_min_timer');
            $ptc_max_timer = get_setting('ptc_max_timer');
            $ptc_min_views = get_setting('ptc_min_views');
            
            if ($validated['timer'] < $ptc_min_timer || $validated['timer'] > $ptc_max_timer) {
                return redirect('/admin/advertise/ptc')->with('message', "Timer must be between $ptc_min_timer and $ptc_max_timer seconds.")->with('type', 'error');
            }
            
            if ($validated['views'] < $ptc_min_views) {
                return redirect('/admin/advertise/ptc')->with('message', "Minimum views required: $ptc_min_views.")->with('type', 'error');
            }
            
            if (!empty($validated['limit_per_day']) && $validated['limit_per_day'] > $validated['views']) {
                return redirect('/admin/advertise/ptc')->with('message', 'Daily limit cannot exceed total views.')->with('type', 'error');
            }
            
            Ptc::create([
                'user_id' => Auth::id(),
                'name' => $validated['name'],
                'description' => $validated['description'],
                'url' => $validated['url'],
                'countries' => $countries,
                'remaining_views' => $validated['views'],
                'timer' => $validated['timer'],
                'type' => $validated['type'],
                'limit_per_day' => $validated['limit_per_day'] ?? 0,
                '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');
        }
    }

    public function updateStatus(Request $request)
    {
        $request->validate([
            'status' => 'required|integer|in:1,2',
            'id' => 'required|integer',
        ]);
        $id = $request->id;
        $ad = Ptc::findOrFail($id);
        $owner = User::findOrFail($ad->user_id);
        if ($request->status == 2) {
            $price_per_sec = ($ad->type == 0) ? get_setting('ptc_iframe_price') : get_setting('ptc_window_price');
            
            $refundAmount = $ad->remaining_views * ($ad->timer * $price_per_sec);
            
            $owner->available_deposit += $refundAmount;
            $owner->save();
            create_notification('Ad Rejected', "Your PTC ad #{$ad->id} was rejected. Refund: $".formatUSD($refundAmount).".", 'warning', $owner->id);
        }else{
            create_notification('Ad Approved', "Your PTC ad #{$ad->id} has been approved.", 'success', $owner->id);
        }
    
        $ad->status = $request->status;
        $ad->save();
    
        return response()->json(['message' => 'Status updated successfully!']);
    }
}
