<?php

namespace Modules\Trip\Models;

use CodeIgniter\Model;
use stdClass;

class SubtripModel extends Model
{
    protected $DBGroup              = 'default';
    protected $table                = 'subtrips';
    protected $primaryKey           = 'id';
    protected $useAutoIncrement     = true;
    protected $insertID             = 0;
    protected $returnType           = 'object';
    protected $useSoftDeletes       = true;
    protected $protectFields        = true;
    protected $allowedFields        = ['id', 'trip_id', 'pick_location_id', 'drop_location_id', 'stoppage', 'adult_fair', 'child_fair', 'special_fair', 'type', 'status', 'show', 'imglocation','distance', 'subtrip_seatclass', 'journey_hour'];

    // Dates 
    protected $useTimestamps        = true;
    protected $dateFormat           = 'datetime';
    protected $createdField         = 'created_at';
    protected $updatedField         = 'updated_at';
    protected $deletedField         = 'deleted_at';

    // Validation
    protected $validationRules      = [];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks       = true;
    protected $beforeInsert         = [];
    protected $afterInsert          = [];
    protected $beforeUpdate         = [];
    protected $afterUpdate          = [];
    protected $beforeFind           = [];
    protected $afterFind            = [];
    protected $beforeDelete         = [];
    protected $afterDelete          = [];

    public function getGroup(): array
    {
        $subtrips = $this->select('subtrips.type, subtrips.trip_id')->findAll();

        return array_values(array_reduce($subtrips, function ($accumulator, $item) {
            if ($item->type == 'main') {
                $trip_id = $item->trip_id;

                // take the children if you already have 
                $children = ($accumulator[$trip_id])->children ?? [];

                $item->children = $children;
                $accumulator[$trip_id] = $item;
                return $accumulator;
            }

            // add a new parent if you haven't already 
            $parent = $item->trip_id;
            if (!isset($accumulator[$parent])) {
                // how did you find the dad will first add only with children 
                $c = new stdClass;
                $c->children = [$item];

                $accumulator[$parent] = $c;
                return $accumulator;
            }

            ($accumulator[$parent])->children[] = $item;
            return $accumulator;
        }, []));
    }

    public function withLocations(): SubtripModel
    {
        return $this
            ->select('l1.name AS picklocation, l2.name AS droplocation')
            ->join('locations l1', 'subtrips.pick_location_id = l1.id')
            ->join('locations l2', 'subtrips.drop_location_id = l2.id')
            ->where('l1.deleted_at IS NULL')
            ->where('l2.deleted_at IS NULL');
    }

    public function active(): SubtripModel
    {
        return $this->where('subtrips.status = 1');
    }


    public function getTripsByCompany($companyIds)
    {
        
        if (!is_array($companyIds)) {
            if($companyIds != "all"){
                $companyIds = [$companyIds]; // wrap single value in an array
                $companyIds = array_filter($companyIds); // remove empty/null values
            }
        }

        $trips = $this->select('
                trips.id as trip_id,
                pick_locations.name as picklocation,
                drop_locations.name as droplocation,
                subtrips.id as subtrip_id,
                subtrips.pick_location_id,
                subtrips.drop_location_id
            ')
            ->join('trips', 'trips.id = subtrips.trip_id')
            ->join('locations as pick_locations', 'pick_locations.id = subtrips.pick_location_id')
            ->join('locations as drop_locations', 'drop_locations.id = subtrips.drop_location_id');

        if($companyIds != "all" && is_array($companyIds)){
            $trips->whereIn('trips.company_id', $companyIds);
        }

        $trips = $trips->where('subtrips.status', 1)->where('trips.status', 1)->findAll();
        
        //echo "<pre>";print_r($trips);exit;

        // Group trips and subtrips by trip_id
        $groupedTrips = [];

        foreach ($trips as $trip) {
            $tripKey = $trip->trip_id;

            if (!isset($groupedTrips[$tripKey])) {
                $groupedTrips[$tripKey] = (object) [
                    'picklocation' => $trip->picklocation,
                    'droplocation' => $trip->droplocation,
                    'id' => $trip->trip_id,
                    'children' => []
                ];
            }

            $groupedTrips[$tripKey]->children[] = (object) [
                'id' => $trip->subtrip_id,
                'picklocation' => $trip->picklocation,
                'droplocation' => $trip->droplocation
            ];
        }

        return array_values($groupedTrips);
    }
}
