<?php

namespace App\Http\Controllers;

use App\Helpers\Helper;
use App\Models\Pricing;
use Illuminate\Http\Request;

class PricingController extends Controller
{
    use Helper;

    public function __construct()
    {
        $this->model = new Pricing();
    }

    public function index()
    {
        try {
            $keyword = request()->input('keyword');
            $type = request()->input('type');
            $billingType = request()->input('billing_type');
            $status = request()->input('status');

            $data = $this->model
                ->when($keyword, function ($query) use ($keyword) {
                    $query->where('title', 'Like', "%$keyword%");
                })
                ->when($type !== null && $type !== '', function ($query) use ($type) {
                    $query->where('type', $type);
                })
                ->when($billingType, function ($query) use ($billingType) {
                    $query->where('billing_type', $billingType);
                })
                ->when($status !== null && $status !== '', function ($query) use ($status) {
                    $query->where('status', $status);
                })
                ->orderBy('is_popular', 'desc')
                ->orderBy('price', 'asc')
                ->paginate($this->perPage);

            return returnData(2000, $data);
        } catch (\Exception $exception) {
            return response()->json(returnData(5000, $exception->getMessage(), 'Whoops, Something Went Wrong..!!'));
        }
    }

    /**
     * Get active packages list for frontend purchase dropdown and pricing cards.
     */
    public function getActivePackages()
    {
        try {
            $packages = Pricing::where('status', 1)
                ->orderBy('is_popular', 'desc')
                ->orderBy('price', 'asc')
                ->get();

            return returnData(2000, $packages);
        } catch (\Exception $exception) {
            return returnData(5000, $exception->getMessage(), 'Unable to load packages.');
        }
    }

    public function store(Request $request)
    {
        try {
            $input = $request->all();
            $validate = $this->model->validate($input);
            if ($validate->fails()) {
                return returnData(3000, $validate->errors(), 'Validation Failed');
            }

            $pricing = new Pricing();
            $pricing->fill($input);
            $pricing->billing_type = $request->input('billing_type', 'per_sms');
            $pricing->sms_limit = (int) $request->input('sms_limit', 0);
            $pricing->daily_limit = (int) $request->input('daily_limit', 0);
            $pricing->masking_rate = $request->filled('masking_rate') ? (float) $request->input('masking_rate') : null;
            $pricing->non_masking_rate = $request->filled('non_masking_rate') ? (float) $request->input('non_masking_rate') : null;
            $pricing->is_popular = $request->input('is_popular', 0) ? 1 : 0;
            $pricing->status = $request->input('status', 1);
            $pricing->save();

            return returnData(2000, $pricing, 'Package Successfully Created');

        } catch (\Exception $exception) {
            return returnData(5000, $exception->getMessage(), 'Whoops, Something Went Wrong..!!');
        }
    }

    public function show($id)
    {
        try {
            $data = Pricing::find($id);
            if (!$data) {
                return returnData(5000, null, 'Package not found');
            }
            return returnData(2000, $data);
        } catch (\Exception $exception) {
            return returnData(5000, $exception->getMessage());
        }
    }

    public function update(Request $request, $id)
    {
        try {
            $input = $request->all();
            $targetId = $input['id'] ?? $id;

            $data = Pricing::where('id', $targetId)->first();

            if (!$data) {
                return returnData(5000, null, 'Data not found');
            }

            $validate = $this->model->validate($input);
            if ($validate->fails()) {
                return returnData(3000, $validate->errors(), 'Validation Failed');
            }

            $data->fill($input);
            $data->billing_type = $request->input('billing_type', $data->billing_type ?: 'per_sms');
            $data->sms_limit = (int) $request->input('sms_limit', $data->sms_limit ?: 0);
            $data->daily_limit = (int) $request->input('daily_limit', $data->daily_limit ?: 0);
            $data->masking_rate = $request->filled('masking_rate') ? (float) $request->input('masking_rate') : $data->masking_rate;
            $data->non_masking_rate = $request->filled('non_masking_rate') ? (float) $request->input('non_masking_rate') : $data->non_masking_rate;
            $data->is_popular = $request->input('is_popular', 0) ? 1 : 0;
            $data->status = $request->input('status', $data->status);
            $data->save();

            return returnData(2000, $data, 'Package Successfully Updated');

        } catch (\Exception $exception) {
            return returnData(5000, $exception->getMessage(), 'Whoops, Something Went Wrong..!!');
        }
    }

    public function destroy($id)
    {
        try {
            $data = Pricing::find($id);
            if (!$data) {
                return returnData(5000, null, 'Package not found');
            }

            $data->delete();
            return returnData(2000, null, 'Package Successfully Deleted');
        } catch (\Exception $exception) {
            return returnData(5000, $exception->getMessage());
        }
    }
}
