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

class Users extends CI_Controller {

	 function __construct()
     {
          parent::__construct();
          $this->load->database();
          $this->load->model('user_model');
          $this->load->model('common');
          $this->load->helper(array('form', 'url','string'));
          $this->load->library('form_validation');
          $this->load->library('session');
     }

	public function index()
	{
		// Get all customer users from Firebase
		$allUsers = $this->common->readdatafromcollectionwhereclause('Users', 'userRole', '=', 'customer');
		
		if (empty($allUsers)) {
			$allUsers = array();
		}
		
		// Enhance user data with order history summary
		$allOrders = $this->common->readdatafromcollectionwhereclause('Orders');
		$userOrders = array();
		
		foreach ($allOrders as $orderId => $order) {
			if (isset($order['userId'])) {
				$userId = $order['userId'];
				if (!isset($userOrders[$userId])) {
					$userOrders[$userId] = array(
						'totalOrders' => 0,
						'totalSpent' => 0,
						'completedOrders' => 0
					);
				}
				$userOrders[$userId]['totalOrders']++;
				if (isset($order['totalAmount'])) {
					$userOrders[$userId]['totalSpent'] += floatval($order['totalAmount']);
				}
				if (isset($order['orderStatus']) && in_array($order['orderStatus'], array('delivered', 'deliver', 'rate', 'rated', 'completed'))) {
					$userOrders[$userId]['completedOrders']++;
				}
			}
		}
		
		// Enhance users with additional information
		$enhancedUsers = array();
		foreach ($allUsers as $userId => $user) {
			$enhancedUsers[$userId] = $user;
			
			// Add account status
			$isSuspended = isset($user['isSuspended']) ? $user['isSuspended'] : false;
			$isActive = isset($user['isActive']) ? $user['isActive'] : true;
			
			if ($isSuspended) {
				$enhancedUsers[$userId]['accountStatus'] = 'Suspended';
			} elseif ($isActive) {
				$enhancedUsers[$userId]['accountStatus'] = 'Active';
			} else {
				$enhancedUsers[$userId]['accountStatus'] = 'Inactive';
			}
			
			// Add order history summary
			if (isset($userOrders[$userId])) {
				$enhancedUsers[$userId]['orderHistorySummary'] = $userOrders[$userId];
			} else {
				$enhancedUsers[$userId]['orderHistorySummary'] = array(
					'totalOrders' => 0,
					'totalSpent' => 0,
					'completedOrders' => 0
				);
			}
			
			// Format registration date
			if (isset($user['registrationDate'])) {
				$enhancedUsers[$userId]['registrationDateFormatted'] = date('Y-m-d H:i:s', $user['registrationDate'] / 1000);
			} elseif (isset($user['createdAt'])) {
				$enhancedUsers[$userId]['registrationDateFormatted'] = date('Y-m-d H:i:s', $user['createdAt'] / 1000);
			} else {
				$enhancedUsers[$userId]['registrationDateFormatted'] = 'N/A';
			}
		}
		
		$data['userlist'] = $enhancedUsers;
		$this->template->template_render('user_management',$data);
	}
	public function adduser()
	{
		$this->template->template_render('user_add');
	}
	public function insertuser() 
	{
		if(isset($_POST)){
			$response = $this->user_model->add_user($this->input->post());
			if($response) {
				$this->session->set_flashdata('successmessage', 'New user added successfully..');
			} else {
				$this->session->set_flashdata('warningmessage', 'Error in creating new user..');
			}
			redirect('users');
		} else {
			$this->session->set_flashdata('warningmessage', 'Error! Your input are not allowed.Please try again');
			redirect('users');
		}
	}
	public function edituser()
	{
		$u_id = $this->uri->segment(3);
		$data['userdetails'] = $this->user_model->get_userdetails($u_id);
		$this->template->template_render('user_add',$data);
	}

	public function updateuser()
	{
		if(isset($_POST)){
			$response = $this->user_model->update_user($this->input->post());
				if($response) {
					$this->session->set_flashdata('successmessage', 'user updated successfully..');
				    redirect('users');
				} else
				{
					$this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
				    redirect('users');
				}
		} else {
			$this->session->set_flashdata('warningmessage', 'Error! Your input are not allowed.Please try again');
			redirect('users');
		}
	}

	/**
	 * Suspend user account temporarily
	 */
	public function suspenduser($id)
	{
		$this->load->model('common');
		$data = array(
			'isSuspended' => true,
			'isActive' => false
		);
		$response = $this->common->updatedatamodel('Users', $id, $data);
		if ($response) {
			$this->session->set_flashdata('successmessage', 'User account suspended successfully');
		} else {
			$this->session->set_flashdata('warningmessage', 'Failed to suspend user account');
		}
		redirect('users');
	}

	/**
	 * Activate user account (remove suspension)
	 */
	public function activateuser($id)
	{
		$this->load->model('common');
		$data = array(
			'isSuspended' => false,
			'isActive' => true
		);
		$response = $this->common->updatedatamodel('Users', $id, $data);
		if ($response) {
			$this->session->set_flashdata('successmessage', 'User account activated successfully');
		} else {
			$this->session->set_flashdata('warningmessage', 'Failed to activate user account');
		}
		redirect('users');
	}

	/**
	 * Delete user account permanently
	 */
	public function deleteuser($id)
	{
		$this->load->model('common');
		$this->load->model('customer_model');
		
		// Delete from Firebase Auth first (if customer_model has delete method)
		if (method_exists($this->customer_model, 'delete_customer')) {
			$authDeleted = $this->customer_model->delete_customer($id);
			if (!$authDeleted) {
				$this->session->set_flashdata('warningmessage', 'Failed to delete user from authentication system');
				redirect('users');
				return;
			}
		}
		
		// Delete from Firestore
		$response = $this->common->deletedatamodel('Users', $id);
		if ($response) {
			$this->session->set_flashdata('successmessage', 'User account deleted permanently');
		} else {
			$this->session->set_flashdata('warningmessage', 'Failed to delete user account');
		}
		redirect('users');
	}

	/**
	 * View user profile with order history
	 */
	public function viewuser($id)
	{
		$this->load->model('common');
		$user = $this->user_model->get_userdetails($id);
		
		if (empty($user)) {
			$this->session->set_flashdata('warningmessage', 'User not found');
			redirect('users');
			return;
		}
		
		// Get user's order history
		$allOrders = $this->common->readdatafromcollectionwhereclause('Orders', 'userId', '=', $id);
		$orderHistory = array();
		
		if (!empty($allOrders)) {
			foreach ($allOrders as $orderId => $order) {
				$orderHistory[$orderId] = array(
					'orderId' => $orderId,
					'orderDate' => isset($order['date']) ? date('Y-m-d H:i:s', $order['date'] / 1000) : 'N/A',
					'orderStatus' => isset($order['orderStatus']) ? $order['orderStatus'] : 'pending',
					'totalAmount' => isset($order['totalAmount']) ? number_format($order['totalAmount'], 2) : '0.00',
					'totalQuantity' => isset($order['totalQuantity']) ? $order['totalQuantity'] : 0
				);
			}
		}
		
		$data['userdetails'] = $user;
		$data['orderHistory'] = $orderHistory;
		$data['orderHistorySummary'] = array(
			'totalOrders' => count($orderHistory),
			'totalSpent' => 0,
			'completedOrders' => 0,
			'cancelledOrders' => 0
		);
		
		foreach ($orderHistory as $order) {
			if (isset($order['totalAmount'])) {
				$amount = floatval(str_replace(',', '', $order['totalAmount']));
				$data['orderHistorySummary']['totalSpent'] += $amount;
			}
			if ($order['orderStatus'] == 'delivered' || $order['orderStatus'] == 'completed') {
				$data['orderHistorySummary']['completedOrders']++;
			} elseif ($order['orderStatus'] == 'cancelled') {
				$data['orderHistorySummary']['cancelledOrders']++;
			}
		}
		
		$data['orderHistorySummary']['totalSpent'] = number_format($data['orderHistorySummary']['totalSpent'], 2);
		
		$this->template->template_render('user_view', $data);
	}
}
