<?php
defined('BASEPATH') or exit('No direct script access allowed');

class FleetOwnerDashboard extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->library('session');
        $this->load->library('template');
        $this->load->model('FleetOwnerDashboard_model');
        $this->load->model('common');
        
        // // Check if user is logged in and is a fleet owner
        // if (empty($this->session->userdata('session_data')) || 
        //     $this->session->userdata('session_data')['role'] != 'fleet') {
        //     redirect(base_url('login'));
        // }
    }

    public function index()
    {
        $fleetOwnerId = $this->session->userdata('session_data')['userId'];
        
        // Get all drivers for this fleet owner
        $drivers = $this->FleetOwnerDashboard_model->get_fleet_drivers($fleetOwnerId);
        $driverIds = array_keys($drivers);
        
        // Get dashboard data
        $data['drivers'] = $drivers;
        $data['driverCount'] = count($drivers);
        $data['revenue'] = $this->FleetOwnerDashboard_model->get_total_revenue($driverIds);
        $data['ridesStats'] = $this->FleetOwnerDashboard_model->get_rides_statistics($driverIds);
        $data['driverPerformance'] = $this->FleetOwnerDashboard_model->get_driver_performance($driverIds);
        $data['paymentHistory'] = $this->FleetOwnerDashboard_model->get_payment_history($fleetOwnerId, 20);
        $data['balances'] = $this->FleetOwnerDashboard_model->get_balances($fleetOwnerId, $driverIds);
        $data['recentRides'] = $this->FleetOwnerDashboard_model->get_recent_rides($driverIds, 10);
        
        // Set active menu for sidebar
        $data['active'] = 'fleet_dashboard';
        
        // Add driver names to performance data
        foreach ($data['driverPerformance'] as $driverId => &$performance) {
            if (isset($drivers[$driverId])) {
                $performance['driverName'] = isset($drivers[$driverId]['fullName']) 
                    ? $drivers[$driverId]['fullName'] 
                    : (isset($drivers[$driverId]['firstName']) ? $drivers[$driverId]['firstName'] : 'Unknown');
                $performance['driverEmail'] = isset($drivers[$driverId]['email']) ? $drivers[$driverId]['email'] : '';
            }
        }
        
        // Add driver names to balances
        foreach ($data['balances']['drivers'] as $driverId => &$balance) {
            if (isset($drivers[$driverId])) {
                $balance['driverName'] = isset($drivers[$driverId]['fullName']) 
                    ? $drivers[$driverId]['fullName'] 
                    : (isset($drivers[$driverId]['firstName']) ? $drivers[$driverId]['firstName'] : 'Unknown');
                $balance['driverEmail'] = isset($drivers[$driverId]['email']) ? $drivers[$driverId]['email'] : '';
            }
        }
        
        $this->template->template_render('fleet_owner_dashboard', $data);
    }

    public function drivers()
    {
        $fleetOwnerId = $this->session->userdata('session_data')['userId'];
        
        // Get all drivers for this fleet owner with details
        $drivers = $this->FleetOwnerDashboard_model->get_fleet_drivers_with_details($fleetOwnerId);
        
        $data['drivers'] = $drivers;
        $data['driverCount'] = count($drivers);
        $data['active'] = 'fleet_drivers';
        
        $this->template->template_render('fleet_drivers', $data);
    }

    public function rides()
    {
        $fleetOwnerId = $this->session->userdata('session_data')['userId'];
        
        // Get all drivers for this fleet owner
        $drivers = $this->FleetOwnerDashboard_model->get_fleet_drivers($fleetOwnerId);
        $driverIds = array_keys($drivers);
        
        // Get all rides for these drivers
        $rides = $this->FleetOwnerDashboard_model->get_fleet_rides($driverIds);
        
        $data['rides'] = $rides;
        $data['rideCount'] = count($rides);
        $data['active'] = 'fleet_rides';
        
        $this->template->template_render('fleet_rides', $data);
    }

    public function driving_hours()
    {
        $fleetOwnerId = $this->session->userdata('session_data')['userId'];
        
        // Get all drivers for this fleet owner
        $drivers = $this->FleetOwnerDashboard_model->get_fleet_drivers($fleetOwnerId);
        $driverIds = array_keys($drivers);
        
        // Get driving hours
        $drivingHours = $this->FleetOwnerDashboard_model->get_driving_hours($driverIds);
        $dailyLimit = $this->FleetOwnerDashboard_model->get_daily_driving_limit();
        $fatigueAlerts = $this->FleetOwnerDashboard_model->get_fatigue_alerts($driverIds, $dailyLimit);
        
        // Add driver names to hours data
        foreach ($drivingHours as $driverId => &$hours) {
            if (isset($drivers[$driverId])) {
                $hours['driverName'] = isset($drivers[$driverId]['fullName']) 
                    ? $drivers[$driverId]['fullName'] 
                    : (isset($drivers[$driverId]['firstName']) ? $drivers[$driverId]['firstName'] : 'Unknown');
                $hours['driverEmail'] = isset($drivers[$driverId]['email']) ? $drivers[$driverId]['email'] : '';
            }
        }
        
        $data['drivingHours'] = $drivingHours;
        $data['fatigueAlerts'] = $fatigueAlerts;
        $data['dailyLimit'] = $dailyLimit;
        $data['drivers'] = $drivers;
        $data['active'] = 'fleet_driving_hours';
        
        $this->template->template_render('fleet_driving_hours', $data);
    }

    public function identity_verification()
    {
        $fleetOwnerId = $this->session->userdata('session_data')['userId'];
        
        // Get all drivers for this fleet owner
        $drivers = $this->FleetOwnerDashboard_model->get_fleet_drivers($fleetOwnerId);
        $driverIds = array_keys($drivers);
        
        // Get identity verifications
        $verifications = $this->FleetOwnerDashboard_model->get_identity_verifications($driverIds, 50);
        
        // Add driver names to verification data
        foreach ($verifications as &$verification) {
            if (isset($verification['driverId']) && isset($drivers[$verification['driverId']])) {
                $verification['driverName'] = isset($drivers[$verification['driverId']]['fullName']) 
                    ? $drivers[$verification['driverId']]['fullName'] 
                    : (isset($drivers[$verification['driverId']]['firstName']) ? $drivers[$verification['driverId']]['firstName'] : 'Unknown');
                $verification['driverImage'] = isset($drivers[$verification['driverId']]['image']) ? $drivers[$verification['driverId']]['image'] : '';
            }
        }
        
        $data['verifications'] = $verifications;
        $data['drivers'] = $drivers;
        $data['active'] = 'fleet_identity_verification';
        
        $this->template->template_render('fleet_identity_verification', $data);
    }

    public function save_driving_limit()
    {
        $limit = $this->input->post('dailyLimit');
        
        if ($limit && is_numeric($limit) && $limit > 0) {
            $this->FleetOwnerDashboard_model->save_daily_driving_limit($limit);
            $this->session->set_flashdata('successmessage', 'Daily driving limit updated successfully!');
        } else {
            $this->session->set_flashdata('warningmessage', 'Invalid driving limit value!');
        }
        
        redirect(base_url('FleetOwnerDashboard/driving_hours'));
    }
}

