<?php

namespace Modules\Coupon\Controllers\Api;

use App\Controllers\BaseController;
use Modules\Coupon\Models\CouponModel;
use Modules\Coupon\Models\CouponDetailsModel;
use CodeIgniter\API\ResponseTrait;

class Coupon extends BaseController
{

	protected $couponModel;
	protected $couponDetailsModel;
	use ResponseTrait;
	public function __construct()
    {
		$this->couponModel = new CouponModel();
		$this->couponDetailsModel = new CouponDetailsModel();
    }


	public function couponValidation($coupon,$subtripId,$journeyDate)
	{
		$journeyDate = date("Y-m-d",strtotime($journeyDate));
		// $validDetail = $this->couponModel->where('code',$coupon)
		// 				->where('subtrip_id',$subtripId)
		// 				->where('end_date >=',$journeyDate)
		// 				->where('start_date <=',$journeyDate)
		// 				->findAll();
		$validDetail = $this->couponDetailsModel
                            ->join('coupons', 'coupons.id = coupon_details.coupon_id', 'left')
                            ->where('coupons.code', $coupon)
                            ->where('coupons.coupon_for', 1)
                            ->where("JSON_CONTAINS(coupon_details.sub_trip_id, '\"$subtripId\"')")
                            ->where('coupons.end_date >=', $journeyDate)
                            ->where('coupons.start_date <=', $journeyDate)
                            ->findAll();
		

		if (count($validDetail) == 0) {
			$data = [
				'status' => "fail",
				'response' => 204,
				'message' =>'coupon is not valid',
				
			];
			return $this->response->setJSON($data);
		}
		else
		{
			$data = [
				'status' => "success",
				'response' => 200,
				'discount' => $validDetail[0]->discount??$validDetail[0]['discount'],
                'discount_type' => $validDetail[0]->discount_type??$validDetail[0]['discount_type'],
                'data' => json_encode($validDetail),
			];
	
			return $this->response->setJSON($data);

		}
		
	}
}
