<?php



namespace Modules\Offer\Controllers\Api;



use App\Controllers\BaseController;

use Modules\Offer\Models\OfferModel;

use Modules\Offer\Models\OfferDetailsModel;

use Modules\Company\Models\CompanyModel;

use Modules\Trip\Models\TripModel;

use Modules\Trip\Models\SubtripModel;



class Offer extends BaseController

{

    protected $offerModel;

    protected $offerDetailsModel;

    protected $companyModel;

    protected $tripModel;

    protected $subtripModel;



    public function __construct()

    {

        $this->offerModel = new OfferModel();

        $this->offerDetailsModel = new OfferDetailsModel();

        $this->companyModel = new CompanyModel();

        $this->tripModel = new TripModel();

        $this->subtripModel = new SubtripModel();

    }



    public function offerValidation($code, $tripId, $companyId)

    {

        $offer = \App\Libraries\OfferTripEligibility::findActiveOfferByCode((string) $code);

        if (! $offer) {

            return $this->response->setJSON([

                'success' => false,

                'message' => 'Invalid offer code'

            ]);

        }



        $subtrip = $this->subtripModel->find((int) $tripId);

        $mainTripId = is_object($subtrip) ? (int) $subtrip->trip_id : (int) $tripId;

        $subtripId = is_object($subtrip) ? (int) $subtrip->id : (int) $tripId;



        if (! \App\Libraries\OfferTripEligibility::appliesToSubtrip($offer, $mainTripId, $subtripId, (int) $companyId)) {

            return $this->response->setJSON([

                'success' => false,

                'message' => 'Invalid offer code'

            ]);

        }



        return $this->response->setJSON([

            'success' => true,

            'offer' => $offer

        ]);

    }



    /**

     * Get all active offers with complete information for mobile app

     * 

     * @return \CodeIgniter\HTTP\ResponseInterface

     */

    public function getAllOffers()

    {

        try {

            $currentDate = date('Y-m-d');

            

            // Get all active offers

            $offers = $this->offerModel

                ->where('start_date <=', $currentDate)

                ->where('end_date >=', $currentDate)

                ->where('deleted_at', null)

                ->findAll();





            $offerData = [];



            foreach ($offers as $offer) {

                // Convert object to array for easier handling

                $offer = (array) $offer;

                

                // Get offer details (companies and trips)

                $offerDetails = $this->offerDetailsModel

                    ->where('offer_id', $offer['id'])

                    ->where('deleted_at', null)

                    ->findAll();



                $companies = [];

                $trips = [];

                $subtrips = [];



                // Process offer details if they exist

                if (!empty($offerDetails)) {

                    foreach ($offerDetails as $detail) {

                        // Convert object to array for easier handling

                        $detail = (array) $detail;

                        

                        // Get company information

                        $companyIds = explode(',', $detail['company_id']);

                        $companyNames = [];

                        foreach ($companyIds as $companyId) {

                            $company = $this->companyModel->find($companyId);
    //                         $company = $this->companyModel
    // ->where('id', $companyId)
    // ->where('status', 1)
    // ->first();


                            if ($company) {

                                $company = (array) $company;

                                if (!in_array($company, $companies)) {
                                    $companyNames[] = $company['name'];
                                    $companies[] = [

                                        'id' => $company['id'],

                                        'name' => $company['name'],

                                        'logo' => $company['logo'] ?? null,

                                        'contact_number' => $company['contact_number'] ?? null,

                                        'email' => $company['email'] ?? null

                                    ];

                                }

                            }

                        }
                        $companyNames = array_unique($companyNames);



                        // Get trip information

                        $trip = $this->tripModel->find($detail['main_trip_id']);

                        if ($trip) {

                            $trip = (array) $trip;

                            $trips[] = [

                                'id' => $trip['id'],

                                'name' => $trip['name'] ?? "",

                                'from_location' => $trip['from_location'] ?? "",

                                'to_location' => $trip['to_location'] ?? ""

                            ];

                        }



                        // Get subtrip information

                        $subtripIds = json_decode($detail['sub_trip_id'], true) ?? [];

                        foreach ($subtripIds as $subtripId) {

                            $subtrip = $this->subtripModel->find($subtripId);

                            if ($subtrip) {

                                $subtrip = (array) $subtrip;

                                $subtrips[] = [

                                    'id' => $subtrip['id'],

                                    'name' => $subtrip['name']??"",

                                    'trip_id' => $subtrip['trip_id'],

                                    'from_location' => $subtrip['from_location']??"",

                                    'to_location' => $subtrip['to_location']??"",

                                    'departure_time' => $subtrip['departure_time']??"",

                                    'arrival_time' => $subtrip['arrival_time']??""

                                ];

                            }

                        }

                }

                }



                // Decode JSON fields

                $seatClasses = !empty($offer['seat_class']) ? json_decode($offer['seat_class'], true) : [];

                $tripCategories = !empty($offer['trip_category']) ? json_decode($offer['trip_category'], true) : [];



                // Build offer data

                $offerData[] = [

                    'id' => $offer['id'],

                    'code' => $offer['code'],

                    'title' => $offer['offer_title'],

                    'description' => $offer['offer_description'],

                    'start_date' => $offer['start_date'],

                    'end_date' => $offer['end_date'],

                    'booking_start_date' => $offer['booking_start_date'],

                    'booking_end_date' => $offer['booking_end_date'],

                    'travel_start_date' => $offer['travel_start_date'],

                    'travel_end_date' => $offer['travel_end_date'],

                    'min_passengers' => (int)$offer['min_passengers'],

                    'discount' => (float)$offer['discount'],

                    'discount_type' => (int)$offer['discount_type'], // 1=Fixed Amount, 2=Percentage

                    'discount_cap' => $offer['discount_cap'] ? (float)$offer['discount_cap'] : null,

                    'min_discount' => $offer['min_discount'] ? (float)$offer['min_discount'] : null,

                    'max_discount' => $offer['max_discount'] ? (float)$offer['max_discount'] : null,

                    'terms_conditions' => $offer['condition'],

                    'offer_image' => $offer['offer_image'] ? base_url('public/uploads/offers/' . $offer['offer_image']) : null,

                    'seat_classes' => $seatClasses,

                    'trip_categories' => $tripCategories,

                    'companies' => $companies,

                    'company_names' => $companyNames,

                    'trips' => $trips,

                    'subtrips' => $subtrips,

                    'is_active' => true,

                    'created_at' => $offer['created_at'],

                    'updated_at' => $offer['updated_at']

                ];

            }



            return $this->response->setJSON([

                'success' => true,

                'message' => 'Offers retrieved successfully',

                'data' => [

                    'offers' => $offerData,

                    'total_count' => count($offerData),

                    'current_date' => $currentDate

                ]

            ]);



        } catch (\Exception $e) {

            return $this->response->setJSON([

                'success' => false,

                'message' => 'Error retrieving offers: ' . $e->getMessage(),

                'data' => null

            ])->setStatusCode(500);

        }

    }



    /**

     * Get offer by ID with complete information

     * 

     * @param int $id

     * @return \CodeIgniter\HTTP\ResponseInterface

     */

    public function getOfferById($id)

    {

        try {

            $offer = $this->offerModel->find($id);

            

            if (!$offer) {

                return $this->response->setJSON([

                    'success' => false,

                    'message' => 'Offer not found',

                    'data' => null

                ])->setStatusCode(404);

            }



            // Convert object to array for easier handling

            $offer = (array) $offer;



            // Get offer details

            $offerDetails = $this->offerDetailsModel

                ->where('offer_id', $offer['id'])

                ->where('deleted_at', null)

                ->findAll();



            $companies = [];

            $trips = [];

            $subtrips = [];



            // Process offer details if they exist

            if (!empty($offerDetails)) {

                foreach ($offerDetails as $detail) {

                    // Convert object to array for easier handling

                    $detail = (array) $detail;

                    

                    // Get company information

                    $companyIds = explode(',', $detail['company_id']);

                    foreach ($companyIds as $companyId) {

                        $company = $this->companyModel->find($companyId);

                        if ($company) {

                            $company = (array) $company;

                            if (!in_array($company, $companies)) {

                                $companies[] = [

                                    'id' => $company['id'],

                                    // 'name' => $company['name'],

                                    'logo' => $company['logo'] ?? null,

                                    'contact_number' => $company['contact_number'] ?? null,

                                    'email' => $company['email'] ?? null

                                ];

                            }

                        }

                    }



                    // Get trip information

                    $trip = $this->tripModel->find($detail['main_trip_id']);

                    if ($trip) {

                        $trip = (array) $trip;

                        $trips[] = [

                            'id' => $trip['id'],

                            // 'name' => $trip['name'],

                            // 'from_location' => $trip['from_location'],

                            'to_location' => $trip['to_location']

                        ];

                    }



                    // Get subtrip information

                    $subtripIds = json_decode($detail['sub_trip_id'], true) ?? [];

                    foreach ($subtripIds as $subtripId) {

                        $subtrip = $this->subtripModel->find($subtripId);

                        if ($subtrip) {

                            $subtrip = (array) $subtrip;

                            $subtrips[] = [

                                'id' => $subtrip['id'],

                                // 'name' => $subtrip['name'],

                                'trip_id' => $subtrip['trip_id'],

                                // 'from_location' => $subtrip['from_location'],

                                'to_location' => $subtrip['to_location'],

                                // 'departure_time' => $subtrip['departure_time'],

                                // 'arrival_time' => $subtrip['arrival_time']

                            ];

                        }

                    }

                }

            }



            // Decode JSON fields

            $seatClasses = !empty($offer['seat_class']) ? json_decode($offer['seat_class'], true) : [];

            $tripCategories = !empty($offer['trip_category']) ? json_decode($offer['trip_category'], true) : [];



            $offerData = [

                'id' => $offer['id'],

                'code' => $offer['code'],

                'title' => $offer['offer_title'],

                'description' => $offer['offer_description'],

                'start_date' => $offer['start_date'],

                'end_date' => $offer['end_date'],

                'booking_start_date' => $offer['booking_start_date'],

                'booking_end_date' => $offer['booking_end_date'],

                'travel_start_date' => $offer['travel_start_date'],

                'travel_end_date' => $offer['travel_end_date'],

                'min_passengers' => (int)$offer['min_passengers'],

                'discount' => (float)$offer['discount'],

                'discount_type' => (int)$offer['discount_type'],

                'discount_cap' => $offer['discount_cap'] ? (float)$offer['discount_cap'] : null,

                'min_discount' => $offer['min_discount'] ? (float)$offer['min_discount'] : null,

                'max_discount' => $offer['max_discount'] ? (float)$offer['max_discount'] : null,

                'terms_conditions' => $offer['condition'],

                'offer_image' => $offer['offer_image'] ? base_url('public/uploads/offers/' . $offer['offer_image']) : null,

                'seat_classes' => $seatClasses,

                'trip_categories' => $tripCategories,

                'companies' => $companies,

                'trips' => $trips,

                'subtrips' => $subtrips,

                'is_active' => $offer['start_date'] <= date('Y-m-d') && $offer['end_date'] >= date('Y-m-d'),

                'created_at' => $offer['created_at'],

                'updated_at' => $offer['updated_at']

            ];



            return $this->response->setJSON([

                'success' => true,

                'message' => 'Offer retrieved successfully',

                'data' => $offerData

            ]);



        } catch (\Exception $e) {

            return $this->response->setJSON([

                'success' => false,

                'message' => 'Error retrieving offer: ' . $e->getMessage(),

                'data' => null

            ])->setStatusCode(500);

        }

    }

}

