<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\PricingPlan;
use App\Models\PromoCode;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\JsonResponse;
class PromoController extends Controller
{
    public function index()
    {
        $promos = PromoCode::orderBy('created_at', 'desc')->get();
        
        return view('admin.promos.index', compact('promos'));

    }
    public function create(){
        $promo = "";
        $plans = PricingPlan::orderBy('created_at', 'desc')->get();

        return view('admin.promos.create', compact('promo', 'plans'));

    }

    public function store(Request $request)
    {
        $rules = [
            'code' => 'required|string|max:255',
            'type' => 'required|in:percentage,fixed',
            'value' => 'required|integer',
            'start_date' => 'required|string',
            'end_date' => 'required|string',
            'total_limit' => 'nullable|integer',
            'user_limit' => 'nullable|integer',
            'daily_limit' => 'nullable|integer',
            'status' => 'required|in:0,1',
            'pricing_plan_id' => 'nullable|array',
            'pricing_plan_id.*' => 'exists:pricing_plans,id',
        ];
    
        $validator = Validator::make($request->all(), $rules);
    
        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'errors' => $validator->errors(),
            ], 422);
        }
    
        if ($request->id) {
            $promo = PromoCode::find($request->id);
    
            if (!$promo) {
                return response()->json(['status' => 'error', 'message' => 'Promo Code not found'], 404);
            }
    
            $existingCity = PromoCode::where('code', $request->code)
                ->where('id', '!=', $request->id)
                ->first();
    
            if ($existingCity) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'code' => ['The Promo code already exists.']
                    ]
                ], 422);
            }
    
            $promo->code = $request->code;
            $promo->type = $request->type;
            $promo->value = $request->value;
            $promo->start_date = $request->start_date;
            $promo->end_date = $request->end_date;
            $promo->total_limit = $request->total_limit;
            $promo->user_limit = $request->user_limit;
            $promo->daily_limit = $request->daily_limit;
            $promo->status = $request->status;
            $promo->pricing_plan_id = $request->pricing_plan_id ? json_encode($request->pricing_plan_id) : '';
            $promo->save();
    
            return response()->json(['status' => 'success', 'message' => 'Promo updated successfully']);
        } else {
            $existingCity = PromoCode::where('code', $request->code)->first();
    
            if ($existingCity) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'name' => ['The Promo name already exists.']
                    ]
                ], 422);
            }
    
            $promo = PromoCode::create([
                'code' => $request->code,
                'type' => $request->type,
                'value' => $request->value,
                'start_date' => $request->start_date,
                'end_date' => $request->end_date,
                'total_limit' => $request->total_limit,
                'user_limit' => $request->user_limit,
                'daily_limit' => $request->daily_limit,
                'status' => $request->status,
                'pricing_plan_id' => $request->pricing_plan_id ? json_encode($request->pricing_plan_id) : '',
            ]);
    
            return response()->json(['status' => 'success', 'message' => 'Promo added successfully', 'promo' => $promo]);
        }
    }
    


  
    public function edit($id) {
        $promo = PromoCode::findOrFail($id);
        $plans = PricingPlan::orderBy('created_at', 'desc')->get();

        return view('admin.promos.create', compact('promo', 'plans'));
    }

    public function destroy($id): JsonResponse
    {
        try {
            $emirate = PromoCode::findOrFail($id);           
            $emirate->delete();
            return response()->json([
                'status' => 'success',
                'message' => 'Promo deleted successfully.'
            ], 200);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Promo not found.'
            ], 404);
        } catch (Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while deleting the company.'
            ], 500);
        }
    }

    public function statusChange(Request $request, $id) {
        $promo = PromoCode::find($id);

        if (!$promo) {
            return response()->json([
                'status' => 'error',
                'message' => 'Promo not found.'
            ], 404);
        }
    
        $promo->status = $request->status;
        $promo->save();
    
        return response()->json([
            'status' => 'success',
            'message' => 'Promo status updated successfully.'
        ]);
    }
}
