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

class Dashboard extends CI_Controller
{

  function __construct()
  {
    parent::__construct();
    // $this->load->database();
    $this->load->helper('url');
    $this->load->library('session');
    $this->load->model('dashboard_model');
    $this->load->model('common');
    $this->load->model('order_model');
  }
  
  public function settings()
  {
    $data["settings"] = $this->common->readdatafromcollectionbetween("Settings");
    
    
    $this->template->template_render('settings', $data);
  }

  public function courses()
  {
    $data["courses"] = $this->common->readdatafromcollectionbetween("Courses");
    
    $this->template->template_render('courses', $data);
  }
  
  public function addcourse()
  {
    $data["categories"] = $this->common->readdatafromcollectionbetween("Categories");
    $data["teams"] = $this->common->readdatafromcollectionbetween("Teams");
    
    $this->template->template_render('addcourse', $data);
  }

  public function insertcourse()
	{
		
		$post = $this->input->post();
    
    $answers = $post['answer'];
    $questionsArray = array();
    foreach($post['question'] as $key => $question) {
      $questionsArray[$key]['question'] = $question[0];
      $theseAnswers = $answers[$key];
      foreach($theseAnswers as $answer) {
        $questionsArray[$key]['answers'][] = $answer;
      }
    }
    
    
    $firebase = $this->firebase->init();
    $storage = $firebase->createStorage();
    $defaultBucket = $storage->getBucket();

    $videoUrl = '';
    if (!empty($_FILES)) {
      foreach($_FILES['video']['tmp_name'] as $key => $value) {
        if ($_FILES['video']['tmp_name'][$key] != '') {
            $name = "Videos/video" . rand() . time() . $_FILES['video']['name'][$key];
            $uploadedFile = $defaultBucket->upload(
                file_get_contents($_FILES['video']['tmp_name'][$key]),
                [
                  'name' => $name,
                  'predefinedAcl' => 'publicRead'
                ]
              );
              $videoUrl = 'https://storage.googleapis.com/athletes-edge-95ced.appspot.com/'.$name;
        }
      }
    }

    $data = [
      'categoryId' => $post['categoryId'],
      'title' => $post['title'],
      'createdDate' => time()*1000,
      'isPro' => $post['isPro']?true:false,
      'rating' => 0,
      'totalTime' => 3,
      'description' => $post['description'],
      'allowedFor' => $post['allowedFor'],
      'allowedTeams' => explode(",",$post['allowedTeams']),
      'questions' => $questionsArray,
      'video' => $videoUrl,
    ];

    $response = $this->common->addnewdatamodel('Courses', $data);

    if ($response) {
      echo('done');
      $this->session->set_flashdata('successmessage', 'Course added successfully..');
    } else {
      echo('not done');
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    // redirect(base_url('dashboard/courses'));		
	}

  public function coaches()
  {
    $data["reelzz"] = [];
    
    
    $this->template->template_render('coaches', $data);
  }
  public function contactus()
  {
    $data["settings"] = $this->common->readdatafromcollectionbetween("Settings");
    
    
    $this->template->template_render('contactus', $data);
  }
  public function resource()
  {
    $data["settings"] = $this->common->readdatafromcollectionbetween("Settings");
    
    
    $this->template->template_render('resource', $data);
  }
  public function appointment()
  {
    $data["settings"] = $this->common->readdatafromcollectionbetween("Settings");
    
    
    $this->template->template_render('appointment', $data);
  }
   public function notifications(){
     $userId = $this->session->userdata('session_data')['userId'];
     $userId="lhZEYNiPlme1EMwKnYU3EkXfiW62";
     $data["notifications"] = $this->common->readdatafromcollectionwhereclause("Notification","userId","=",$userId);
     $this->template->template_render('notifications', $data);
   }

   public function check_unread_notifications()
   {
     header('Content-Type: application/json');
     
     $userId = $this->session->userdata('session_data')['userId'];
     if (!$userId) {
       echo json_encode(['success' => false, 'message' => 'User not authenticated']);
       return;
     }
     
     // Get all notifications for the user
     $notifications = $this->common->readdatafromcollectionwhereclause("Notification", "userId", "=", $userId);
     
     $unreadCount = 0;
     $hasUnread = false;
     
     if ($notifications) {
       foreach ($notifications as $notification) {
         // Check if notification is unread for this user
         if (!isset($notification['isRead'][$userId]) || $notification['isRead'][$userId] != 1) {
           $unreadCount++;
           $hasUnread = true;
         }
       }
     }
     
     echo json_encode([
       'success' => true,
       'hasUnread' => $hasUnread,
       'unreadCount' => $unreadCount,
       'totalNotifications' => count($notifications ?? [])
     ]);
   }

   public function get_notification_status()
   {
     header('Content-Type: application/json');
     
     $userId = $this->session->userdata('session_data')['userId'];
     if (!$userId) {
       echo json_encode(['hasUnread' => false, 'unreadCount' => 0]);
       return;
     }
     
     // Get all notifications for the user
     $notifications = $this->common->readdatafromcollectionwhereclause("Notification", "userId", "=", $userId);
     
     $unreadCount = 0;
     
     if ($notifications) {
       foreach ($notifications as $notification) {
         // Check if notification is unread for this user
         if (!isset($notification['isRead'][$userId]) || $notification['isRead'][$userId] != 1) {
           $unreadCount++;
         }
       }
     }
     
     echo json_encode([
       'hasUnread' => $unreadCount > 0,
       'unreadCount' => $unreadCount
     ]);
   }

  public function questions()
  {
    if(!isset($_SESSION['type'])){

      $_SESSION['type'] = 'morning';
    }

    $type = $this->uri->segment(3);
    if($type){
      $_SESSION['type'] = $type;
    }
    $data["questions"] = $this->common->readdatacollection("Journal", "Questions", $_SESSION['type']);
    
    
    $this->template->template_render('questions', $data);
  }

  public function addQuestion()
  {
    $this->template->template_render('addQuestion');
  }

  public function saveQuestion()
  {
    $post = $this->input->post();
    
    if($post['type'] == 'Checkbox'){
      
      $options = $post['options'];
      unlink($post['options']);
  
      $optionsMap = [];

      foreach($options as $option){
        $optionsMap[$option] = false;
      }
      $post['options'] = $optionsMap;
    }
    if($post['count']){

      $post['count'] = (int)$post['count'];
    }

    if($post['type'] == 'Simple'){
  
      $post['count'] = 1;
      
    }

    if($post['type'] == 'Number'){
  
      $answers = [];

      for($i = 0; $i < $post['count']; $i++){
        $answers[] = '';
      }

      $post['answers'] = $answers;
    }

    $id = time();
    $this->common->adddatamodelnexted("Journal", $_SESSION['type'], "Questions", $id, $post);
    redirect(base_url('dashboard/questions'));
  }
  
//nexteddeletedatamodel
  public function saveSettings($id)
  {
    $post = $this->input->post();
    $response = $this->common->updatedatamodel("Settings", $id, $post);
    if($response) {
				$this->session->set_flashdata('successmessage', 'Settings has been updated');
    }else{
			$this->session->set_flashdata('warningmessage', 'Error! Some issue with firebase.Please try again');
    }

    redirect(base_url('dashboard/settings'));
  }



  public function index()
  {
     $this->session->userdata('session_data')['userId'];
    

     $allrides = $this->common->readdatafromcollectionwhereclause("Bookings","userId","=",$this->session->userdata('session_data')['userId']);
     $currentride = array();
     foreach($allrides as $key => $ride) {
      if($ride['status'] == "booked" || $ride['status'] == "driverRequested" || $ride['status'] == "driverAccepted" || $ride['status'] == "driverReached" || $ride['status'] == "rideStarted" ){
        $currentride[$key] = $ride;
      }
     }
     $data['currentride'] = $currentride;
     $data['rates']=$this->common->readdatadocument("Settings","Prices");
    //  

    $this->template->template_render('dashboard', $data);
  }

  public function myrides($status = 'all')
	{
		// Define available statuses
		$available_statuses = array(
			'process', 'processed', 'confirm', 'confirmed', 
			'shippe', 'shipped', 'cancel', 'cancelled', 
			'deliver', 'delivered', 'rate', 'rated', 
			'dispute', 'disputed'
		);
		
		$data['available_statuses'] = $available_statuses;
		$data['current_status'] = $status;
		
		// Get all rides for the user
	
			$myrides = $this->common->readdatafromcollectionwhereclause('Bookings','userId','=',$this->session->userdata('session_data')['userId']);
   
    $tello=array();

		foreach($myrides as $key => $ride) {
      if($ride['status'] == "driverAccepted" || $ride['status'] == "driverReached" || $ride['status'] == "rideStarted"){
        $tello[$key] = $ride;
      }
		}
		$data['myrides'] = $tello;
    $data['status'] = "ongoing";
		$this->template->template_render('myrides', $data);
	}
  public function complete_ride()
  {
    $id="u8Ru2AhayDa9Y91boZheqVEggcC2";
    $data['status'] = "complete";
    $tello=array();
    $ride = $this->common->readdatafromcollectionwhereclause('Bookings','userId','=',$id);
    foreach($ride as $key => $ride) {
      if($ride['status'] == 'complete' || $ride['status'] == 'rated'){  
        $tello[$key] = $ride;
      $driverId = $ride['driverId'];
      $userId = $ride['userId'];
      $driver = $this->common->readdatadocument('Users', $driverId);
      $user = $this->common->readdatadocument('Users', $userId);
      $tello[$key]['driver'] = $driver;
      $tello[$key]['user'] = $user;
    }
  }
    $data['rides'] = $tello;
    $this->template->template_render('complete_ride', $data);
  }
  public function view_ride($id)
  {
    $data['ride'] = $this->common->readdatadocument('Bookings', $id);
    $this->template->template_render('view_ride', $data);
  }
  public function view_scheduled_ride($id)
  {
    $data['ride'] = $this->common->readdatadocument('ScheduledRides', $id);
    $this->template->template_render('view_scheduled_ride', $data);
  }

  public function cancel_ride()
  {
    header('Content-Type: application/json');
    
    if (!$this->input->post() && !$this->input->raw_input_stream) {
      echo json_encode(['success' => false, 'message' => 'No data received']);
      return;
    }
    
    try {
      $input = json_decode($this->input->raw_input_stream, true);
      
      if (!$input || !isset($input['rideId'])) {
        echo json_encode(['success' => false, 'message' => 'Ride ID is required']);
        return;
      }
      
      $rideId = $input['rideId'];
      $userId = $this->session->userdata('session_data')['userId'];
      
      // Get the ride to verify ownership
      $ride = $this->common->readdatadocument('Bookings', $rideId);
      
      if (!$ride) {
        echo json_encode(['success' => false, 'message' => 'Ride not found']);
        return;
      }
      
      if ($ride['userId'] !== $userId) {
        echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
        return;
      }
      
      // Check if ride can be cancelled (only allow cancellation for certain statuses)
      $cancellableStatuses = ['booked', 'driverRequested', 'driverAccepted'];
      if (!in_array($ride['status'], $cancellableStatuses)) {
        echo json_encode(['success' => false, 'message' => 'This ride cannot be cancelled at this stage']);
        return;
      }
      
      // Update ride status to cancelled
      $updateData = array(
        'status' => 'dispute',
        'cancelledAt' => date('Y-m-d H:i:s'),
        'cancelledBy' => 'user'
      );
      
      $result = $this->common->updatedatamodel('Bookings', $rideId, $updateData);
      
      if ($result) {
        echo json_encode([
          'success' => true,
          'message' => 'Ride cancelled successfully'
        ]);
      } else {
        echo json_encode(['success' => false, 'message' => 'Failed to cancel ride']);
      }
      
    } catch (Exception $e) {
      echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
    }
  }
  public function schedule_ride()
  {
    $userId=$this->session->userdata('session_data')['userId'];
    $data['status'] = "schedule";
    $data['rides'] = $this->common->readdatafromcollectionwhereclause('ScheduledRides','userId','=',$userId);
   
    $this->template->template_render('schedule_ride', $data);
  }
  public function changepassword()
  {
    $this->template->template_render('changepassword');
  }

  public function update_password()
  {
    header('Content-Type: application/json');
    
    if($this->input->post()) {
      $newPassword = $this->input->post('newPassword');
      $confirmPassword = $this->input->post('confirmPassword');
      $userId = $this->session->userdata('session_data')['userId'];
      
      // Validation
      if(empty($newPassword) || empty($confirmPassword)) {
        echo json_encode(['success' => false, 'message' => 'All fields are required']);
        return;
      }
      
      if(strlen($newPassword) < 8) {
        echo json_encode(['success' => false, 'message' => 'New password must be at least 8 characters long']);
        return;
      }
      
      if($newPassword !== $confirmPassword) {
        echo json_encode(['success' => false, 'message' => 'New password and confirmation do not match']);
        return;
      }
      
      // Get current user data
      $userData = $this->common->readdatadocument('Users', $userId);
      
      if(!$userData) {
        echo json_encode(['success' => false, 'message' => 'User not found']);
        return;
      }
      
      try {
        // Initialize Firebase Auth
        $firebase = $this->firebase->init();
        $auth = $firebase->createAuth();
        
        // Update password in Firebase Auth
        $userRecord = $auth->getUser($userId);
        $updatedUser = $auth->updateUser($userId, [
          'password' => $newPassword
        ]);
        
        if($updatedUser) {
          // Update password info in Firestore Users collection
          $updateData = array(
            'passwordUpdatedAt' => date('Y-m-d H:i:s'),
            'passwordChangeCount' => isset($userData['passwordChangeCount']) ? $userData['passwordChangeCount'] + 1 : 1
          );
          
          $result = $this->common->updatedatamodel('Users', $userId, $updateData);
          
          echo json_encode([
            'success' => true, 
            'message' => 'Password updated successfully in Firebase Auth!'
          ]);
        } else {
          echo json_encode(['success' => false, 'message' => 'Failed to update password in Firebase Auth']);
        }
        
      } catch (Exception $e) {
        // Handle Firebase Auth errors
        $errorMessage = $e->getMessage();
        
        // Parse common Firebase Auth errors
        if (strpos($errorMessage, 'user-not-found') !== false) {
          echo json_encode(['success' => false, 'message' => 'User not found in Firebase Auth']);
        } elseif (strpos($errorMessage, 'weak-password') !== false) {
          echo json_encode(['success' => false, 'message' => 'Password is too weak. Please choose a stronger password.']);
        } elseif (strpos($errorMessage, 'invalid-password') !== false) {
          echo json_encode(['success' => false, 'message' => 'Invalid password format']);
        } else {
          echo json_encode(['success' => false, 'message' => 'Firebase Auth error: ' . $errorMessage]);
        }
      }
      
    } else {
      echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    }
  }


public function message($conversationid="")
	{
     $id = $this->session->userdata('session_data')['userId'];
    $data=array();
     
     $key='participants.'.$id;
     $conversations = $this->common->readdatafromcollectionwhereclause('Chats', $key, '=', true);
     
     // Process conversations to include user data
     $processedConversations = array();
     foreach($conversations as $conversationKey => $conversation) {
         if(isset($conversation['lastMessage'])) {
             // Determine which user to fetch (the other participant)
             if ($conversation['lastMessage']['fromID'] == $id) {
                 $otherUserId = $conversation['lastMessage']['toID'];
             } else {
                 $otherUserId = $conversation['lastMessage']['fromID'];
             }
             
             // Fetch user data
             $userData = $this->common->readdatadocument('Users', $otherUserId);
             $conversation['otherUser'] = $userData;
         }
         $processedConversations[$conversationKey] = $conversation;
     }
     
     $data['conversations'] = $processedConversations;
     
     if($conversationid==""){
       $data['chatlist']="";
       $data['selectedConversation'] = null;
     }else{
       $data['chatlist']=$this->common->readdatacollection('Chats',"Conversations", $conversationid);
       
       // Get selected conversation data
       if(isset($processedConversations[$conversationid])) {
           $data['selectedConversation'] = $processedConversations[$conversationid];
       } else {
           // If conversation not found in processed list, get it directly
           $selectedChat = $this->common->readdatadocument('Chats', $conversationid);
           if($selectedChat && isset($selectedChat['participants'][$id])) {
               // Get other participant
               foreach($selectedChat['participants'] as $participantId => $isActive) {
                   if($participantId !== $id && $isActive === true) {
                       $otherUser = $this->common->readdatadocument('Users', $participantId);
                       $selectedChat['otherUser'] = $otherUser;
                       $selectedChat['otherUserId'] = $participantId;
                       break;
                   }
               }
               $data['selectedConversation'] = $selectedChat;
           }
       }
     }
     
     $data['conversationId'] = $conversationid;

    $data['userId'] = $id;
		$this->template->template_render('message', $data);
	}

	public function send_message()
	{
		header('Content-Type: application/json');
		
		if($this->input->post()) {
			$conversationId = $this->input->post('conversationId');
			$messageText = trim($this->input->post('message'));
			$currentUserId = $this->session->userdata('session_data')['userId'];
			
			if($conversationId && $messageText && $currentUserId) {
				// Get conversation to find other participant
				$conversation = $this->common->readdatadocument('Chats', $conversationId);
				
				if($conversation && isset($conversation['participants'][$currentUserId])) {
					// Find other participant
					$receiverId = '';
					foreach($conversation['participants'] as $participantId => $isActive) {
						if($participantId !== $currentUserId && $isActive === true) {
							$receiverId = $participantId;
							break;
						}
					}
					
					if($receiverId) {
						$timestamp = time() * 1000;
						
						// Create message data
						$messageData = array(
							'messageId' => uniqid(),
							'fromID' => $currentUserId,
							'toID' => $receiverId,
							'content' => $messageText,
							'timestamp' => $timestamp,
							'type' => 'text',
							'isRead' => false
						);
						
						$key = time().rand();
						// Save message to subcollection: Chats/{conversationId}/Conversations
						$messageId = $this->common->adddatamodelnexted('Chats', $conversationId, 'Conversations', $key, $messageData);
						
						if($messageId) {
							// Update conversation's lastMessage
							$conversationUpdate = array(
								'lastMessage' => array(
									'fromID' => $currentUserId,
									'toID' => $receiverId,
									'content' => $messageText,
									'timestamp' => $timestamp
								),
								'updatedAt' => date('Y-m-d H:i:s')
							);
							$this->common->updatedatamodel('Chats', $conversationId, $conversationUpdate);
							
							// Return success response with message data
							echo json_encode([
								'success' => true,
								'message' => 'Message sent successfully!',
								'messageData' => [
									'id' => $key,
									'content' => $messageText,
									'fromID' => $currentUserId,
									'timestamp' => $timestamp,
									'formattedTime' => date('g:i A', $timestamp / 1000)
								]
							]);
						} else {
							echo json_encode(['success' => false, 'message' => 'Failed to save message']);
						}
					} else {
						echo json_encode(['success' => false, 'message' => 'Could not find recipient for this conversation']);
					}
				} else {
					echo json_encode(['success' => false, 'message' => 'Invalid conversation or access denied']);
				}
			} else {
				echo json_encode(['success' => false, 'message' => 'Message cannot be empty']);
			}
		} else {
			echo json_encode(['success' => false, 'message' => 'Invalid request method']);
		}
	}

	public function get_messages()
	{
		header('Content-Type: application/json');
		
		$conversationId = $this->input->get('conversationId');
		$lastTimestamp = $this->input->get('lastTimestamp');
		$currentUserId = $this->session->userdata('session_data')['userId'];
		
		if($conversationId && $currentUserId) {
			// Verify user has access to this conversation
			$conversation = $this->common->readdatadocument('Chats', $conversationId);
			
			if($conversation && isset($conversation['participants'][$currentUserId])) {
				// Get all messages
				$messages = $this->common->readdatacollection('Chats', "Conversations", $conversationId);
				
				if($messages) {
					// Filter messages newer than lastTimestamp if provided
					if($lastTimestamp) {
						$filteredMessages = array();
						foreach($messages as $messageId => $message) {
							if($message['timestamp'] > $lastTimestamp) {
								$filteredMessages[$messageId] = $message;
							}
						}
						$messages = $filteredMessages;
					}
					
					// Sort messages by timestamp
					uasort($messages, function($a, $b) {
						return $a['timestamp'] - $b['timestamp'];
					});
					
					// Format messages for frontend
					$formattedMessages = array();
					foreach($messages as $messageId => $message) {
						$formattedMessages[] = [
							'id' => $messageId,
							'content' => $message['content'],
							'fromID' => $message['fromID'],
							'toID' => $message['toID'],
							'timestamp' => $message['timestamp'],
							'formattedTime' => date('g:i A', $message['timestamp'] / 1000),
							'isSent' => ($message['fromID'] == $currentUserId)
						];
					}
					
					echo json_encode([
						'success' => true,
						'messages' => $formattedMessages,
						'lastTimestamp' => !empty($messages) ? max(array_column($messages, 'timestamp')) : $lastTimestamp
					]);
				} else {
					echo json_encode(['success' => true, 'messages' => [], 'lastTimestamp' => $lastTimestamp]);
				}
			} else {
				echo json_encode(['success' => false, 'message' => 'Access denied']);
			}
		} else {
			echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
		}
	}







  public function book_ride()
	{
		header('Content-Type: application/json');
		
		// Get JSON input
		$input = json_decode($this->input->raw_input_stream, true);
   	
		if (!$input) {
			echo json_encode(['success' => false, 'message' => 'Invalid request data']);
			return;
		}
		
		// Validate required fields
		$required_fields = ['pickLocation', 'pickupLatitude', 'pickupLongitude', 'dropLocation', 'dropLatitude', 'dropLongitude', 'bookingType'];
		
		foreach ($required_fields as $field) {
			if (!isset($input[$field]) || empty($input[$field])) {
				echo json_encode(['success' => false, 'message' => 'Missing required field: ' . $field]);
				return;
			}
		}
		
		try {
			$userId = $this->session->userdata('session_data')['userId'];

      $c['carType']="iRide";
     // $c['destinations'][0]=$input['destinations'];
      $c['destinations'][0]['address']=$input['dropLocation'];
      $c['destinations'][0]['lat']=$input['dropLatitude'];
      $c['destinations'][0]['lng']=$input['dropLongitude'];
      $c['destinations'][0]['status']="0";
 
      $c['pickUp']['address']=$input['pickupLocation'];
      $c['pickUp']['lat']=$input['pickupLatitude'];
      $c['pickUp']['lng']=$input['pickupLongitude'];
      $c['pickUp']['status']="0";

      $c['driverPrice']=$input['paymentDetails']['amount'];
      $c['pickupDate']=time()*1000;
      $c['price']=$input['paymentDetails']['amount'];
      $c['rideType']="zero";
      $c['status']="booked";
      $c['userId']=$userId;
      $c['createdAt']=date('Y-m-d H:i:s');

      $c['pm_id']=$input['paymentDetails']['paymentIntentId'];
      $c['bookingaddedby']="Web";
     


     $tell=array();
      $routeDetails=$input['routeDetails']['directionsResult']['routes'][0]['legs'][0]['steps'];
      $c['distance']=$input['routeDetails']['distance'];
      $c['distanceValue']=$input['routeDetails']['distanceValue'];
      $c['time']=$input['routeDetails']['duration'];
      $c['timeValue']=$input['routeDetails']['durationValue'];
      foreach($routeDetails as $key => $routeDetail){
        $tell[$key]['distance']=$routeDetail['distance']['value'];

        $tell[$key]['time']=$routeDetail['duration']['value'];
        $tell[$key]['polyline']=$routeDetail['polyline']['points'];
      }
      $c['routeDetails']=$tell;
      $id="booking_".time().rand();
      $c['bookingId']=$id;

      if($input['bookingType'] == "immediate"){
        $c['bookingDate']=time()*1000;
        $c['input']=$input;
        $bookingId = $this->common->adddatamodel('Bookings', $id, $c);
    		if ($bookingId) {
          echo json_encode([
            'success' => true, 
            'message' => 'Ride booked successfully!',
            'bookingId' => $bookingId,
            'data' => $bookingData
          ]);
        } else {
          echo json_encode(['success' => false, 'message' => 'Failed to save booking']);
        }
    
      }else{
        $c['bookingDate']=strtotime($input['bookingDateTime'])*1000;
        $bookingId = $this->common->adddatamodel('ScheduledRides', $id, $c);
        if ($bookingId) {
          echo json_encode([
            'success' => true, 
            'message' => 'Scheduled Ride booked successfully!',
            'bookingId' => $bookingId,
            'data' => $bookingData
          ]);
        } else {
          echo json_encode(['success' => false, 'message' => 'Failed to save booking']);
        }
    
      }

			/*
			
			// Add payment details if payment was processed

			if (isset($input['paymentDetails'])) {
				$bookingData['paymentDetails'] = $input['paymentDetails'];
				$bookingData['totalAmount'] = $input['paymentDetails']['amount'];
				$bookingData['paymentStatus'] = 'paid';
			}
			
			// Add scheduled date if it's a scheduled booking
			if ($input['bookingType'] === 'schedule' && isset($input['bookingDateTime'])) {
				$bookingData['scheduledDateTime'] = $input['bookingDateTime'];
			} else {
				$bookingData['scheduledDateTime'] = null; // Immediate booking
			}
			
			// Add route details if provided from frontend
			if (isset($input['routeDetails'])) {
				$bookingData['routeDetails'] = $input['routeDetails'];
				$bookingData['estimatedDistance'] = $input['routeDetails']['distanceValue'] / 1000; // Convert to km
				$bookingData['estimatedDuration'] = $input['routeDetails']['durationValue'] / 60; // Convert to minutes
			} else {
				// Fallback: Calculate basic distance using Haversine formula
				$distance = $this->calculateDistance(
					$input['pickupLatitude'], 
					$input['pickupLongitude'],
					$input['dropLatitude'], 
					$input['dropLongitude']
				);
				$bookingData['estimatedDistance'] = $distance;
				$bookingData['estimatedDuration'] = $distance * 2; // Rough estimate: 2 minutes per km
			}
			*/
			// Save booking to database
	
			
			
		} catch (Exception $e) {
			echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
		}
	}
	
	// Calculate distance between two coordinates (Haversine formula)
	private function calculateDistance($lat1, $lon1, $lat2, $lon2) {
		$earthRadius = 6371; // Earth's radius in kilometers
		
		$dLat = deg2rad($lat2 - $lat1);
		$dLon = deg2rad($lon2 - $lon1);
		
		$a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLon/2) * sin($dLon/2);
		$c = 2 * atan2(sqrt($a), sqrt(1-$a));
		
		$distance = $earthRadius * $c; // Distance in kilometers
		
		return round($distance, 2);
	}

	// Process Stripe payment
	public function process_payment()
	{
		header('Content-Type: application/json');
		
		// Get JSON input
		$input = json_decode($this->input->raw_input_stream, true);
		
		if (!$input || !isset($input['amount']) || !isset($input['payment_method_id'])) {
			echo json_encode(['success' => false, 'message' => 'Invalid payment data']);
			return;
		}
		
		try {
			// Load Stripe via Composer autoloader
			$composerAutoload = FCPATH . 'vendor/autoload.php';
			if (!file_exists($composerAutoload)) {
				echo json_encode([
					'success' => false,
					'message' => 'Composer autoload not found at ' . $composerAutoload . '. Run composer install.'
				]);
				return;
			}
			require_once $composerAutoload;
			
			// Set Stripe secret key
			\Stripe\Stripe::setApiKey('sk_test_51KAaUIBGRgAEMSr6hO5k6wty9ZieD9VHKJuiN3ZQlSCrKuGzzgsL3NtQ1ixEjndOcjefZDp8L1XAl7TAFGOChND700hFHgstKW'); // Replace with your secret key
			
			$amount = $input['amount']; // Amount in cents
			$paymentMethodId = $input['payment_method_id'];
			
			// Create payment intent
			$paymentIntent = \Stripe\PaymentIntent::create([
				'amount' => $amount,
				'currency' => $input['currency'],
				'payment_method' => $paymentMethodId,
				'confirmation_method' => 'manual',
				'confirm' => true,
				'return_url' => base_url('dashboard/payment_return'),
				'metadata' => [
					'booking_type' => $input['bookingData']['bookingType'],
					'user_id' => $this->session->userdata('session_data')['userId']
				]
			]);
			
			if ($paymentIntent->status === 'succeeded') {
				// Payment successful
				$paymentDetails = array(
					'paymentIntentId' => $paymentIntent->id,
					'amount' => $amount / 100, // Convert back to dollars
					'currency' => $input['currency'],
					'status' => 'paid',
					'paymentMethod' => 'stripe',
					'paidAt' => date('Y-m-d H:i:s')
				);
				
				echo json_encode([
					'success' => true,
					'paymentDetails' => $paymentDetails,
					'message' => 'Payment processed successfully'
				]);
			} else {
				echo json_encode([
					'success' => false,
					'message' => 'Payment not completed. Status: ' . $paymentIntent->status
				]);
			}
			
		} catch (\Stripe\Exception\CardException $e) {
			// Card was declined
			echo json_encode([
				'success' => false,
				'message' => 'Your card was declined: ' . $e->getError()->message
			]);
		} catch (\Stripe\Exception\InvalidRequestException $e) {
			// Invalid parameters
			echo json_encode([
				'success' => false,
				'message' => 'Invalid payment request: ' . $e->getMessage()
			]);
		} catch (Exception $e) {
			// Other errors
			echo json_encode([
				'success' => false,
				'message' => 'Payment error: ' . $e->getMessage()
			]);
		}
	}

  public function profile()
  {
    $data['user'] = $this->common->readdatadocument('Users', $this->session->userdata('session_data')['userId']);
    $this->template->template_render('profile', $data);
  }

  public function update_profile()
  {
    header('Content-Type: application/json');
    
    if (!$this->input->post()) {
        echo json_encode(['success' => false, 'message' => 'No data received']);
        return;
    }
    
    try {
        $userId = $this->session->userdata('session_data')['userId'];
        
        // Get current user data
        $currentUser = $this->common->readdatadocument('Users', $userId);
        
        if (!$currentUser) {
            echo json_encode(['success' => false, 'message' => 'User not found']);
            return;
        }
        
        // Prepare update data (only allow certain fields to be updated)
        $updateData = array();
        
        $allowedFields = ['firstName', 'userName'];
        
        foreach ($allowedFields as $field) {
            if ($this->input->post($field) !== null) {
                $updateData[$field] = trim($this->input->post($field));
            }
        }
        
        // Validate required fields
        if (empty($updateData['firstName'])) {
            echo json_encode(['success' => false, 'message' => 'First name is required']);
            return;
        }
        
        if (empty($updateData['userName'])) {
            echo json_encode(['success' => false, 'message' => 'User name is required']);
            return;
        }
        
        // Add update timestamp
        $updateData['updatedAt'] = date('Y-m-d H:i:s');
        
        // Update user document
        $result = $this->common->updatedatamodel('Users', $userId, $updateData);
        
        if ($result) {
            echo json_encode([
                'success' => true,
                'message' => 'Profile updated successfully',
                'data' => $updateData
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to update profile']);
        }
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
    }
  }

  public function upload_profile_image()
  {
    header('Content-Type: application/json');
    
    if (!isset($_FILES['profile_image'])) {
        echo json_encode(['success' => false, 'message' => 'No image file received']);
        return;
    }
    
    $file = $_FILES['profile_image'];
    
    // Validate file
    if ($file['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['success' => false, 'message' => 'File upload error']);
        return;
    }
    
    // Check file size (5MB limit)
    if ($file['size'] > 5 * 1024 * 1024) {
        echo json_encode(['success' => false, 'message' => 'File size must be less than 5MB']);
        return;
    }
    
    // Check file type
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimeType = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);
    
    if (!in_array($mimeType, $allowedTypes)) {
        echo json_encode(['success' => false, 'message' => 'Invalid file type. Only JPG, PNG, GIF, and WebP are allowed']);
        return;
    }
    
    try {
        $userId = $this->session->userdata('session_data')['userId'];
        
        // Initialize Firebase Storage
        $firebase = $this->firebase->init();
        $storage = $firebase->createStorage();
        $defaultBucket = $storage->getBucket();
        
        $imageUrl = '';
        if (!empty($_FILES)) {
            if ($_FILES['profile_image']['tmp_name'] != '') {
                // Generate unique filename for Firebase Storage
                $extension = pathinfo($_FILES['profile_image']['name'], PATHINFO_EXTENSION);
                $name = "ProfileImages/" . $userId . "_" . rand() . time() . "." . $extension;
                
                // Upload to Firebase Storage
                $uploadedFile = $defaultBucket->upload(
                    file_get_contents($_FILES['profile_image']['tmp_name']),
                    [
                        'name' => $name,
                        'predefinedAcl' => 'publicRead'
                    ]
                );
                
                // Get the public URL
                $imageUrl = $uploadedFile->info()['mediaLink'];
            }
        }
        
        if (!empty($imageUrl)) {
            // Update user document with new image URL
            $updateData = array(
                'image' => $imageUrl,
                'profileImageUpdated' => date('Y-m-d H:i:s')
            );
            
            $result = $this->common->updatedatamodel('Users', $userId, $updateData);
            
            if ($result) {
                echo json_encode([
                    'success' => true,
                    'message' => 'Profile image updated successfully',
                    'imageUrl' => $imageUrl
                ]);
            } else {
                // If database update fails, optionally delete the uploaded file from Firebase
                try {
                    $uploadedFile->delete();
                } catch (Exception $deleteError) {
                    // Log delete error but don't fail the response
                    error_log('Failed to delete uploaded file: ' . $deleteError->getMessage());
                }
                echo json_encode(['success' => false, 'message' => 'Failed to update profile in database']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to upload image to Firebase Storage']);
        }
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Upload error: ' . $e->getMessage()]);
    }
  }
  

	// Create payment intent (alternative method)
	public function create_payment_intent()
	{
		header('Content-Type: application/json');
		
		$input = json_decode($this->input->raw_input_stream, true);
		
		if (!$input || !isset($input['amount'])) {
			echo json_encode(['error' => 'Amount required']);
			return;
		}
		
		try {
			// Load Stripe library
			require_once APPPATH . 'libraries/stripe/init.php';
			\Stripe\Stripe::setApiKey('sk_test_51KAaUIBGRgAEMSr6hO5k6wty9ZieD9VHKJuiN3ZQlSCrKuGzzgsL3NtQ1ixEjndOcjefZDp8L1XAl7TAFGOChND700hFHgstKW');
			
			$paymentIntent = \Stripe\PaymentIntent::create([
				'amount' => $input['amount'],
				'currency' => $input['currency'],
				'metadata' => [
					'user_id' => $this->session->userdata('session_data')['userId'],
					'booking_type' => $input['bookingData']['bookingType']
				]
			]);
			
			echo json_encode([
				'client_secret' => $paymentIntent->client_secret
			]);
			
		} catch (Exception $e) {
			echo json_encode(['error' => $e->getMessage()]);
		}
	}

  public function categories()
	{

		$data['categories'] = $this->common->readdatafromcollectionwhereclause('Categories');
		$this->template->template_render('categories', $data);
	}

  public function addservicetype()
	{

		$this->template->template_render('addservicetype');
	}

  public function addcategory()
	{

		$this->template->template_render('addcategory');
	}

  public function insertquote()
	{
		
		$post = $this->input->post();
    $data['quote'] = $post['quote'];
    $data['createdDate'] = time()*1000;
    $data['isActive'] = true;
    $response = $this->common->addnewdatamodel('Quotes', $data);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Quote added successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/quotes'));		
	}

  public function editquote()
	{
		$id = $this->uri->segment(3);
    $data['id'] = $id;
		$data['quote'] = $this->common->readdatadocument('Quotes', $id);
    if(!$data['quote']){
      redirect(base_url('dashboard/quotes'));
    }
		$this->template->template_render('editquote', $data);
	}

  public function updatequote()
	{
    $post = $this->input->post();
    $data['quote'] = $post['quote'];

		$response = $this->common->updatedatamodel('Quotes', $post['id'], $data);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Quote updated successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/quotes'));
	}

  public function deletequote()
	{
    $id = $this->uri->segment(3);

		$response = $this->common->deletedatamodel('Quotes', $id);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Quote deleted successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/quotes'));
	}

  public function deleteCourse()
	{
    $id = $this->uri->segment(3);

		$response = $this->common->deletedatamodel('Courses', $id);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Course deleted successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/courses'));
	}

  public function deleteQuestion()
	{
    $id = $this->uri->segment(3);

		$response = $this->common->nexteddeletedatamodel('Journal', $_SESSION['type'], 'Questions', $id);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Question deleted successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/questions'));
	}
  public function insertcategory()
	{
		$post = $this->input->post();
    $data['name'] = $post['name'];
    $data['id'] = time();
    $response = $this->common->addnewdatamodel('Categories', $data);
    if ($response) {
      $this->session->set_flashdata('successmessage', 'Category added successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }
    redirect(base_url('dashboard/categories'));
	}
  public function updatecategory()
	{
		$post = $this->input->post();
    $data['name'] = $post['name'];
    $response = $this->common->updatedatamodel('Categories', $post['id'], $data);
   
    if ($response) {
      $this->session->set_flashdata('successmessage', 'Category updated successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }
    redirect(base_url('dashboard/categories'));
	}
  
  public function insertservicetype()
	{
		
		$post = $this->input->post();
    $data['name'] = $post['name'];

    $firebase = $this->firebase->init();
    $storage = $firebase->createStorage();
    $defaultBucket = $storage->getBucket();

    $iconUrl = '';
    if (!empty($_FILES)) {
        if ($_FILES['image']['tmp_name'] != '') {
            $name = "ServiceTypes/image" . rand() . time() . $_FILES['image']['name'];
            $uploadedFile = $defaultBucket->upload(
                file_get_contents($_FILES['image']['tmp_name']),
                [
                  'name' => $name,
                  'predefinedAcl' => 'publicRead'
                ]
              );
              $imageUrl = $uploadedFile->info()['mediaLink'];
        }
    }
    $data['image'] = $imageUrl;
    $data['id'] = time();


    $response = $this->common->adddatamodel('ServiceTypes', $data['id'], $data);

      if ($response) {
      $this->session->set_flashdata('successmessage', 'Service Type added successfully..');
    } else {
        $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/servicetype'));		
	}
	public function editcategory()
	{
		$id = $this->uri->segment(3);
    $data['id'] = $id;
		$data['category'] = $this->common->readdatadocument('Categories', $id);
		$this->template->template_render('addcategory', $data);
	}
  public function editservicetype()
	{
		$id = $this->uri->segment(3);
    $data['id'] = $id;
		$data['servicetype'] = $this->common->readdatadocument('ServiceTypes', $id);
		$this->template->template_render('addservicetype', $data);
	}

	public function updateservicetype()
	{
    $post = $this->input->post();
    $data['name'] = $post['name'];

    $firebase = $this->firebase->init();
    $storage = $firebase->createStorage();
    $defaultBucket = $storage->getBucket();


    if (!empty($_FILES)) {
        if ($_FILES['image']['tmp_name'] != '') {
            $name = "ServiceTypes/image" . rand() . time() . $_FILES['image']['name'];
            $uploadedFile = $defaultBucket->upload(
                file_get_contents($_FILES['image']['tmp_name']),
                [
                  'name' => $name,
                  'predefinedAcl' => 'publicRead'
                ]
              );
              $imageUrl = $uploadedFile->info()['mediaLink'];
              $data['image'] = $imageUrl;
            }
    }

		$response = $this->common->updatedatamodel('ServiceTypes', $post['id'], $data);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Service Type updated successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/servicetype'));
	}
  public function deleteservicetype()
	{
		$id = $this->uri->segment(3);
		$response = $this->common->deletedatamodel('ServiceTypes', $id);
		if ($response) {
      $this->session->set_flashdata('successmessage', 'Service Type deleted successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/servicetype'));
	}

  public function deletecategory()
	{
    $id = $this->uri->segment(3);

		$response = $this->common->deletedatamodel('Categories', $id);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Category deleted successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/categories'));
	}

   public function vendors()
	{

   $this->template->template_render('vendors');
	}
    public function products()
	{
    $data['products'] = $this->common->readdatafromcollectionwhereclause('Products');
   $this->template->template_render('products_management', $data);
	}
	public function viewProduct($id)
	{
		$data['id'] = $id;
		$data['product'] = $this->common->readdatadocument('Products', $id);
		$this->template->template_render('products', $data);
	}
     public function serviceprovider()
	{
   $this->template->template_render('serviceprovider');
	}

  public function orders()
  {
    $filter_type = $this->input->get('filter');
    $start_date = $this->input->get('start_date');
    $end_date = $this->input->get('end_date');
    $status = $this->input->get('status');

    $data = array();
    
    // Set default filter to today if no filter is specified
    if (!$filter_type) {
      $filter_type = 'today';
    }

    switch ($filter_type) {
      case 'today':
        $data['orders'] = $this->order_model->get_today_orders();
        $data['filter_type'] = 'today';
        $data['filter_label'] = 'Today\'s Orders';
        break;
        
      case 'date_range':
        if ($start_date && $end_date) {
          $data['orders'] = $this->order_model->get_orders_with_filters($start_date, $end_date, $status);
          $data['filter_type'] = 'date_range';
          $data['start_date'] = $start_date;
          $data['end_date'] = $end_date;
          $data['status'] = $status;
          $data['filter_label'] = 'Orders from ' . date('M d, Y', strtotime($start_date)) . ' to ' . date('M d, Y', strtotime($end_date));
        } else {
          $data['orders'] = $this->order_model->get_all_orders();
          $data['filter_type'] = 'all';
          $data['filter_label'] = 'All Orders';
        }
        break;
        
      case 'all':
      default:
        $data['orders'] = $this->order_model->get_all_orders();
        $data['filter_type'] = 'all';
        $data['filter_label'] = 'All Orders';
        break;
    }

    // Get order counts for summary
    $data['today_count'] = $this->order_model->get_today_order_count();
    $data['total_count'] = count($this->order_model->get_all_orders());

    $this->template->template_render('orders', $data);
  }

  public function update_order_status()
  {
    $order_id = $this->input->post('order_id');
    $status = $this->input->post('status');
    
    if ($order_id && $status) {
      $response = $this->order_model->update_order_status($order_id, $status);
      
      if ($response) {
        $this->session->set_flashdata('successmessage', 'Order status updated successfully');
      } else {
        $this->session->set_flashdata('warningmessage', 'Failed to update order status');
      }
    } else {
      $this->session->set_flashdata('warningmessage', 'Invalid order data');
    }
    
    redirect(base_url('dashboard/orders'));
  }

  public function delete_order()
  {
    $order_id = $this->uri->segment(3);
    
    if ($order_id) {
      $response = $this->order_model->delete_order($order_id);
      
      if ($response) {
        $this->session->set_flashdata('successmessage', 'Order deleted successfully');
      } else {
        $this->session->set_flashdata('warningmessage', 'Failed to delete order');
      }
    } else {
      $this->session->set_flashdata('warningmessage', 'Invalid order ID');
    }
    
    redirect(base_url('dashboard/orders'));
  }

  public function view_order()
  {
    $order_id = $this->uri->segment(3);
    
    if ($order_id) {
      $data['order'] = $this->order_model->get_order_by_id($order_id);
      
      if ($data['order']) {
        $this->template->template_render('view_order', $data);
      } else {
        $this->session->set_flashdata('warningmessage', 'Order not found');
        redirect(base_url('dashboard/orders'));
      }
    } else {
      $this->session->set_flashdata('warningmessage', 'Invalid order ID');
      redirect(base_url('dashboard/orders'));
    }
  }
}