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

use Google\Cloud\Firestore\FirestoreClient;

class FleetOwnerDashboard_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('common');
    }

    /**
     * Get all drivers associated with a fleet owner
     */
    public function get_fleet_drivers($fleetOwnerId)
    {
        $x = $this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => $this->config->item('firebase_project_id'),
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);

        // Try to get drivers by fleetOwnerId field
        $driversRef = $db->collection('Users')
            ->where('userRole', '=', 'driver')
            ->where('fleetOwnerId', '=', $fleetOwnerId);
        
        $documents = $driversRef->documents();
        $drivers = array();
        
        foreach ($documents as $document) {
            if ($document->exists()) {
                $drivers[$document->id()] = $document->data();
                $drivers[$document->id()]['driverId'] = $document->id();
            }
        }

        // If no drivers found with fleetOwnerId, get all drivers (for backward compatibility)
        if (empty($drivers)) {
            $driversRef = $db->collection('Users')->where('userRole', '=', 'driver');
            $documents = $driversRef->documents();
            foreach ($documents as $document) {
                if ($document->exists()) {
                    $drivers[$document->id()] = $document->data();
                    $drivers[$document->id()]['driverId'] = $document->id();
                }
            }
        }

        return $drivers;
    }

    /**
     * Get total revenue for fleet owner's drivers
     */
    public function get_total_revenue($driverIds = array())
    {
        $x = $this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => $this->config->item('firebase_project_id'),
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);

        $bookingsRef = $db->collection('Bookings');
        $documents = $bookingsRef->documents();
        
        $totalRevenue = 0;
        $todayRevenue = 0;
        $monthRevenue = 0;
        $todayStart = strtotime('today') * 1000;
        $monthStart = strtotime('first day of this month') * 1000;
        $todayEnd = strtotime('tomorrow') * 1000;

        foreach ($documents as $document) {
            if ($document->exists()) {
                $booking = $document->data();
                
                // Filter by driver if driverIds provided
                if (!empty($driverIds) && isset($booking['driverId']) && !in_array($booking['driverId'], $driverIds)) {
                    continue;
                }

                // Only count completed rides
                if (isset($booking['status']) && $booking['status'] == 'rideCompleted' && isset($booking['price'])) {
                    $price = (float)$booking['price'];
                    $totalRevenue += $price;

                    // Today's revenue
                    if (isset($booking['bookingDate']) && $booking['bookingDate'] >= $todayStart && $booking['bookingDate'] < $todayEnd) {
                        $todayRevenue += $price;
                    }

                    // This month's revenue
                    if (isset($booking['bookingDate']) && $booking['bookingDate'] >= $monthStart) {
                        $monthRevenue += $price;
                    }
                }
            }
        }

        return array(
            'total' => $totalRevenue,
            'today' => $todayRevenue,
            'month' => $monthRevenue
        );
    }

    /**
     * Get completed and cancelled rides count
     */
    public function get_rides_statistics($driverIds = array())
    {
        $x = $this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => $this->config->item('firebase_project_id'),
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);

        $bookingsRef = $db->collection('Bookings');
        $documents = $bookingsRef->documents();
        
        $completed = 0;
        $cancelled = 0;
        $todayCompleted = 0;
        $todayCancelled = 0;
        $todayStart = strtotime('today') * 1000;
        $todayEnd = strtotime('tomorrow') * 1000;

        foreach ($documents as $document) {
            if ($document->exists()) {
                $booking = $document->data();
                
                // Filter by driver if driverIds provided
                if (!empty($driverIds) && isset($booking['driverId']) && !in_array($booking['driverId'], $driverIds)) {
                    continue;
                }

                if (isset($booking['status'])) {
                    if ($booking['status'] == 'rideCompleted') {
                        $completed++;
                        if (isset($booking['bookingDate']) && $booking['bookingDate'] >= $todayStart && $booking['bookingDate'] < $todayEnd) {
                            $todayCompleted++;
                        }
                    } elseif ($booking['status'] == 'cancelled') {
                        $cancelled++;
                        if (isset($booking['bookingDate']) && $booking['bookingDate'] >= $todayStart && $booking['bookingDate'] < $todayEnd) {
                            $todayCancelled++;
                        }
                    }
                }
            }
        }

        return array(
            'completed' => $completed,
            'cancelled' => $cancelled,
            'todayCompleted' => $todayCompleted,
            'todayCancelled' => $todayCancelled
        );
    }

    /**
     * Get driver performance metrics
     */
    public function get_driver_performance($driverIds = array())
    {
        $x = $this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => $this->config->item('firebase_project_id'),
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);

        $bookingsRef = $db->collection('Bookings');
        $documents = $bookingsRef->documents();
        
        $driverPerformance = array();
        
        // Initialize driver performance arrays
        foreach ($driverIds as $driverId) {
            $driverPerformance[$driverId] = array(
                'totalRides' => 0,
                'completedRides' => 0,
                'cancelledRides' => 0,
                'totalRevenue' => 0,
                'averageRating' => 0,
                'totalRatings' => 0,
                'ratingSum' => 0
            );
        }

        foreach ($documents as $document) {
            if ($document->exists()) {
                $booking = $document->data();
                
                if (!isset($booking['driverId']) || !in_array($booking['driverId'], $driverIds)) {
                    continue;
                }

                $driverId = $booking['driverId'];
                
                if (!isset($driverPerformance[$driverId])) {
                    $driverPerformance[$driverId] = array(
                        'totalRides' => 0,
                        'completedRides' => 0,
                        'cancelledRides' => 0,
                        'totalRevenue' => 0,
                        'averageRating' => 0,
                        'totalRatings' => 0,
                        'ratingSum' => 0
                    );
                }

                $driverPerformance[$driverId]['totalRides']++;

                if (isset($booking['status'])) {
                    if ($booking['status'] == 'rideCompleted') {
                        $driverPerformance[$driverId]['completedRides']++;
                        if (isset($booking['price'])) {
                            $driverPerformance[$driverId]['totalRevenue'] += (float)$booking['price'];
                        }
                    } elseif ($booking['status'] == 'cancelled') {
                        $driverPerformance[$driverId]['cancelledRides']++;
                    }
                }

                // Get rating if available
                if (isset($booking['rating']) && is_numeric($booking['rating'])) {
                    $driverPerformance[$driverId]['totalRatings']++;
                    $driverPerformance[$driverId]['ratingSum'] += (float)$booking['rating'];
                }
            }
        }

        // Calculate average ratings
        foreach ($driverPerformance as $driverId => &$performance) {
            if ($performance['totalRatings'] > 0) {
                $performance['averageRating'] = round($performance['ratingSum'] / $performance['totalRatings'], 2);
            }
        }

        return $driverPerformance;
    }

    /**
     * Get payment history for fleet owner
     */
    public function get_payment_history($fleetOwnerId, $limit = 50)
    {
        $x = $this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => $this->config->item('firebase_project_id'),
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);

        // Try to get payments from Payouts collection
        $paymentsRef = $db->collection('Payouts')
            ->where('fleetOwnerId', '=', $fleetOwnerId);
        
        $documents = $paymentsRef->documents();
        $payments = array();

        foreach ($documents as $document) {
            if ($document->exists()) {
                $payment = $document->data();
                $payment['paymentId'] = $document->id();
                $payments[] = $payment;
            }
        }

        // If no payments found with fleetOwnerId, try to get all payments (for backward compatibility)
        if (empty($payments)) {
            $paymentsRef = $db->collection('Payouts');
            $documents = $paymentsRef->documents();
            
            foreach ($documents as $document) {
                if ($document->exists()) {
                    $payment = $document->data();
                    $payment['paymentId'] = $document->id();
                    $payments[] = $payment;
                }
            }
        }

        // Sort by timestamp descending
        usort($payments, function($a, $b) {
            $timestampA = isset($a['timestamp']) ? (is_numeric($a['timestamp']) ? $a['timestamp'] : strtotime($a['timestamp']) * 1000) : 0;
            $timestampB = isset($b['timestamp']) ? (is_numeric($b['timestamp']) ? $b['timestamp'] : strtotime($b['timestamp']) * 1000) : 0;
            return $timestampB - $timestampA;
        });

        // Limit results
        $payments = array_slice($payments, 0, $limit);

        return $payments;
    }

    /**
     * Get global and individual driver balances
     */
    public function get_balances($fleetOwnerId, $driverIds = array())
    {
        $x = $this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => $this->config->item('firebase_project_id'),
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);

        $bookingsRef = $db->collection('Bookings');
        $documents = $bookingsRef->documents();
        
        $globalBalance = 0;
        $driverBalances = array();
        
        // Initialize driver balances
        foreach ($driverIds as $driverId) {
            $driverBalances[$driverId] = array(
                'totalEarnings' => 0,
                'paidAmount' => 0,
                'pendingAmount' => 0
            );
        }

        // Calculate earnings from completed rides
        foreach ($documents as $document) {
            if ($document->exists()) {
                $booking = $document->data();
                
                if (!isset($booking['driverId']) || !in_array($booking['driverId'], $driverIds)) {
                    continue;
                }

                if (isset($booking['status']) && $booking['status'] == 'rideCompleted' && isset($booking['price'])) {
                    $price = (float)$booking['price'];
                    $driverId = $booking['driverId'];
                    
                    if (!isset($driverBalances[$driverId])) {
                        $driverBalances[$driverId] = array(
                            'totalEarnings' => 0,
                            'paidAmount' => 0,
                            'pendingAmount' => 0
                        );
                    }
                    
                    $driverBalances[$driverId]['totalEarnings'] += $price;
                    $globalBalance += $price;
                }
            }
        }

        // Get paid amounts from Payouts collection
        $paymentsRef = $db->collection('Payouts');
        $paymentDocs = $paymentsRef->documents();
        
        foreach ($paymentDocs as $paymentDoc) {
            if ($paymentDoc->exists()) {
                $payment = $paymentDoc->data();
                
                if (isset($payment['driverId']) && in_array($payment['driverId'], $driverIds)) {
                    $driverId = $payment['driverId'];
                    if (isset($driverBalances[$driverId]) && isset($payment['amount'])) {
                        $driverBalances[$driverId]['paidAmount'] += (float)$payment['amount'];
                    }
                }
            }
        }

        // Calculate pending amounts
        foreach ($driverBalances as $driverId => &$balance) {
            $balance['pendingAmount'] = $balance['totalEarnings'] - $balance['paidAmount'];
        }

        // Calculate global paid amount
        $globalPaid = 0;
        foreach ($driverBalances as $balance) {
            $globalPaid += $balance['paidAmount'];
        }

        return array(
            'global' => array(
                'totalEarnings' => $globalBalance,
                'paidAmount' => $globalPaid,
                'pendingAmount' => $globalBalance - $globalPaid
            ),
            'drivers' => $driverBalances
        );
    }

    /**
     * Get recent rides for fleet owner
     */
    public function get_recent_rides($driverIds = array(), $limit = 10)
    {
        $x = $this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => $this->config->item('firebase_project_id'),
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);

        $bookingsRef = $db->collection('Bookings');
        $documents = $bookingsRef->documents();
        
        $rides = array();

        foreach ($documents as $document) {
            if ($document->exists()) {
                $booking = $document->data();
                
                if (!empty($driverIds) && isset($booking['driverId']) && !in_array($booking['driverId'], $driverIds)) {
                    continue;
                }

                $ride = $booking;
                $ride['rideId'] = $document->id();
                $rides[] = $ride;
            }
        }

        // Sort by bookingDate descending
        usort($rides, function($a, $b) {
            $dateA = isset($a['bookingDate']) ? $a['bookingDate'] : 0;
            $dateB = isset($b['bookingDate']) ? $b['bookingDate'] : 0;
            return $dateB - $dateA;
        });

        return array_slice($rides, 0, $limit);
    }

    /**
     * Get all rides for fleet owner's drivers with user and driver details
     */
    public function get_fleet_rides($driverIds = array())
    {
        $x = $this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => $this->config->item('firebase_project_id'),
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);

        $bookingsRef = $db->collection('Bookings');
        $documents = $bookingsRef->documents();
        
        $rides = array();

        foreach ($documents as $document) {
            if ($document->exists()) {
                $booking = $document->data();
                
                // Filter by driver if driverIds provided
                if (!empty($driverIds) && isset($booking['driverId']) && !in_array($booking['driverId'], $driverIds)) {
                    continue;
                }

                $ride = $booking;
                $ride['rideId'] = $document->id();
                
                // Get user details
                if (isset($booking['userId'])) {
                    $userDoc = $db->collection('Users')->document($booking['userId'])->snapshot();
                    if ($userDoc->exists()) {
                        $ride['user'] = $userDoc->data();
                    }
                }
                
                // Get driver details
                if (isset($booking['driverId'])) {
                    $driverDoc = $db->collection('Users')->document($booking['driverId'])->snapshot();
                    if ($driverDoc->exists()) {
                        $ride['driver'] = $driverDoc->data();
                    }
                }
                
                $rides[] = $ride;
            }
        }

        // Sort by bookingDate descending
        usort($rides, function($a, $b) {
            $dateA = isset($a['bookingDate']) ? (is_numeric($a['bookingDate']) ? $a['bookingDate'] : strtotime($a['bookingDate']) * 1000) : 0;
            $dateB = isset($b['bookingDate']) ? (is_numeric($b['bookingDate']) ? $b['bookingDate'] : strtotime($b['bookingDate']) * 1000) : 0;
            return $dateB - $dateA;
        });

        return $rides;
    }

    /**
     * Get all drivers with their vehicle information
     */
    public function get_fleet_drivers_with_details($fleetOwnerId)
    {
        $drivers = $this->get_fleet_drivers($fleetOwnerId);
        
        $x = $this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => $this->config->item('firebase_project_id'),
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);

        // Add vehicle information for each driver
        foreach ($drivers as $driverId => &$driver) {
            $vehiclesRef = $db->collection('Vehicle')->where('userId', '=', $driverId);
            $vehicleDocs = $vehiclesRef->documents();
            
            $driver['vehicles'] = array();
            foreach ($vehicleDocs as $vehicleDoc) {
                if ($vehicleDoc->exists()) {
                    $driver['vehicles'][] = $vehicleDoc->data();
                }
            }
            
            $driver['vehicleCount'] = count($driver['vehicles']);
        }

        return $drivers;
    }

    /**
     * Get driving hours for fleet drivers
     */
    public function get_driving_hours($driverIds = array(), $period = 'daily')
    {
        $x = $this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => $this->config->item('firebase_project_id'),
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);

        $bookingsRef = $db->collection('Bookings');
        $documents = $bookingsRef->documents();
        
        $driverHours = array();
        $todayStart = strtotime('today') * 1000;
        $todayEnd = strtotime('tomorrow') * 1000;
        $weekStart = strtotime('monday this week') * 1000;
        $monthStart = strtotime('first day of this month') * 1000;

        // Initialize driver hours
        foreach ($driverIds as $driverId) {
            $driverHours[$driverId] = array(
                'daily' => 0,
                'weekly' => 0,
                'monthly' => 0,
                'total' => 0
            );
        }

        foreach ($documents as $document) {
            if ($document->exists()) {
                $booking = $document->data();
                
                if (!isset($booking['driverId']) || !in_array($booking['driverId'], $driverIds)) {
                    continue;
                }

                // Only count completed rides
                if (isset($booking['status']) && $booking['status'] == 'rideCompleted') {
                    $driverId = $booking['driverId'];
                    
                    if (!isset($driverHours[$driverId])) {
                        $driverHours[$driverId] = array(
                            'daily' => 0,
                            'weekly' => 0,
                            'monthly' => 0,
                            'total' => 0
                        );
                    }

                    // Calculate ride duration
                    $duration = 0;
                    if (isset($booking['startTime']) && isset($booking['endTime'])) {
                        $startTime = is_numeric($booking['startTime']) ? $booking['startTime'] : strtotime($booking['startTime']) * 1000;
                        $endTime = is_numeric($booking['endTime']) ? $booking['endTime'] : strtotime($booking['endTime']) * 1000;
                        $duration = ($endTime - $startTime) / (1000 * 60 * 60); // Convert to hours
                    } elseif (isset($booking['duration'])) {
                        $duration = (float)$booking['duration'] / 60; // Assuming duration is in minutes
                    } elseif (isset($booking['bookingDate']) && isset($booking['completionTimeStamp'])) {
                        $startTime = is_numeric($booking['bookingDate']) ? $booking['bookingDate'] : strtotime($booking['bookingDate']) * 1000;
                        $endTime = is_numeric($booking['completionTimeStamp']) ? $booking['completionTimeStamp'] : strtotime($booking['completionTimeStamp']) * 1000;
                        $duration = ($endTime - $startTime) / (1000 * 60 * 60);
                    }

                    if ($duration > 0) {
                        $driverHours[$driverId]['total'] += $duration;

                        // Daily hours
                        if (isset($booking['bookingDate'])) {
                            $bookingDate = is_numeric($booking['bookingDate']) ? $booking['bookingDate'] : strtotime($booking['bookingDate']) * 1000;
                            if ($bookingDate >= $todayStart && $bookingDate < $todayEnd) {
                                $driverHours[$driverId]['daily'] += $duration;
                            }
                            if ($bookingDate >= $weekStart) {
                                $driverHours[$driverId]['weekly'] += $duration;
                            }
                            if ($bookingDate >= $monthStart) {
                                $driverHours[$driverId]['monthly'] += $duration;
                            }
                        }
                    }
                }
            }
        }

        return $driverHours;
    }

    /**
     * Get fatigue alerts for drivers
     */
    public function get_fatigue_alerts($driverIds = array(), $dailyLimit = 12)
    {
        $driverHours = $this->get_driving_hours($driverIds, 'daily');
        $alerts = array();

        foreach ($driverHours as $driverId => $hours) {
            if ($hours['daily'] >= $dailyLimit) {
                $alerts[] = array(
                    'driverId' => $driverId,
                    'dailyHours' => round($hours['daily'], 2),
                    'limit' => $dailyLimit,
                    'status' => 'exceeded',
                    'message' => 'Driver has exceeded daily driving limit'
                );
            } elseif ($hours['daily'] >= ($dailyLimit * 0.9)) {
                $alerts[] = array(
                    'driverId' => $driverId,
                    'dailyHours' => round($hours['daily'], 2),
                    'limit' => $dailyLimit,
                    'status' => 'warning',
                    'message' => 'Driver approaching daily driving limit'
                );
            }
        }

        return $alerts;
    }

    /**
     * Get identity verification records
     */
    public function get_identity_verifications($driverIds = array(), $limit = 50)
    {
        $x = $this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => $this->config->item('firebase_project_id'),
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);

        // Try to get from IdentityVerifications collection
        $verificationsRef = $db->collection('IdentityVerifications');
        $documents = $verificationsRef->documents();
        
        $verifications = array();

        foreach ($documents as $document) {
            if ($document->exists()) {
                $verification = $document->data();
                
                // Filter by driver if driverIds provided
                if (!empty($driverIds) && isset($verification['driverId']) && !in_array($verification['driverId'], $driverIds)) {
                    continue;
                }

                $verification['verificationId'] = $document->id();
                $verifications[] = $verification;
            }
        }

        // Sort by timestamp descending
        usort($verifications, function($a, $b) {
            $timestampA = isset($a['timestamp']) ? (is_numeric($a['timestamp']) ? $a['timestamp'] : strtotime($a['timestamp']) * 1000) : 0;
            $timestampB = isset($b['timestamp']) ? (is_numeric($b['timestamp']) ? $b['timestamp'] : strtotime($b['timestamp']) * 1000) : 0;
            return $timestampB - $timestampA;
        });

        return array_slice($verifications, 0, $limit);
    }

    /**
     * Get daily driving limit from settings
     */
    public function get_daily_driving_limit()
    {
        $x = $this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => $this->config->item('firebase_project_id'),
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);

        // Try to get from Settings collection
        $settingsRef = $db->collection('Settings')->document('drivingLimits');
        $snapshot = $settingsRef->snapshot();
        
        if ($snapshot->exists()) {
            $settings = $snapshot->data();
            return isset($settings['dailyLimit']) ? (float)$settings['dailyLimit'] : 12; // Default 12 hours
        }

        return 12; // Default 12 hours
    }

    /**
     * Save daily driving limit
     */
    public function save_daily_driving_limit($limit)
    {
        $x = $this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => $this->config->item('firebase_project_id'),
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);

        $settingsRef = $db->collection('Settings')->document('drivingLimits');
        $settingsRef->set([
            'dailyLimit' => (float)$limit,
            'updatedAt' => time() * 1000
        ]);

        return true;
    }
}

