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

class Admin extends CI_Controller
{

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

	public function index()
	{
		$data['admins'] = $this->common->readdatafromcollectionwhereclause("Admins");
		$data['active'] = 'admin';
		$this->template->template_render('admins', $data);
	}

	public function addAdmin()
	{
		$data['active'] = 'admin';
		$this->template->template_render('adminadd', $data);
	}
	//editcustomer
	
public function insertadmin()
{
    try {
        $firebase = $this->firebase->init();
        $auth = $firebase->createAuth();
        
        // Get POST data
        $post = $this->input->post();
        
        // Check if admin with the same email already exists
        $isUserExists = $this->common->readdatafromcollectionwhereclause("Admins", 'email', '=', $post['email']);
        if ($isUserExists) {
            $errormsg = 'Error! Admin with this email already exists.';
            $this->session->set_flashdata('warningmessage', $errormsg);
            redirect(base_url('admin/addAdmin'));
            exit;
        }

        // Prepare user data
        $data = [
            'email' => $post['email'],
            'emailVerified' => true,
            'password' => $post['password'],
            'displayName' => $post['name'],
            'disabled' => false,
        ];

        // Mark the post data as active
        $post['isActive'] = true;

        // Attempt to create the user in Firebase
        try {
            $createdUser = $auth->createUser($data);
        } catch (Exception $e) {
            // Catch Firebase user creation errors
            $errormsg = 'Error creating user in Firebase: ' . $e->getMessage();
            $this->session->set_flashdata('warningmessage', $errormsg);
            redirect(base_url('admin/addAdmin'));
            exit;
        }

        // Store user in the local database
        try {
            $response = $this->common->adddatamodel('Admins', $createdUser->uid, $post);
        } catch (Exception $e) {
            // Catch database insertion errors
            $errormsg = 'Error saving admin data in the database: ' . $e->getMessage();
            $this->session->set_flashdata('warningmessage', $errormsg);
            redirect(base_url('admin/addAdmin'));
            exit;
        }

        // Success message if everything goes well
        if ($response) {
            $this->session->set_flashdata('successmessage', 'New Admin user added successfully');
            redirect(base_url('admin'));
        } else {
            // Fallback error message
            $errormsg = 'Error! Please check your data and try again.';
            $this->session->set_flashdata('warningmessage', $errormsg);
            redirect(base_url('admin/addAdmin'));
        }
    } catch (Exception $e) {
        // Catch any unexpected errors
        $errormsg = 'Unexpected error occurred: ' . $e->getMessage();
        $this->session->set_flashdata('warningmessage', $errormsg);
        redirect(base_url('admin/addAdmin'));
    }
}

	public function editAdmin()
	{
		$uid = $this->uri->segment(3);
		$data['admin'] = $this->common->readdatadocument('Admins', $uid);
		$data['id'] = $uid;
		$data['active'] = 'admin';
		$this->template->template_render('adminadd', $data);
	}

public function updateadmin()
{
    try {
        // Get the POST data
        $post = $this->input->post();

        // Initialize Firebase
        $firebase = $this->firebase->init();
        $auth = $firebase->createAuth();

        // Prepare data for updating the Firebase user
        $data = [
            'displayName' => $post['name'],
            'email' => $post['email'],
            'password' => $post['password'],
        ];

        // Attempt to update user in Firebase
        try {
            $auth->updateUser($post['id'], $data);
        } catch (Exception $e) {
            // Catch Firebase update errors
            $errormsg = 'Error updating user in Firebase: ' . $e->getMessage();
            $this->session->set_flashdata('warningmessage', $errormsg);
            redirect(base_url('admin'));
            return;
        }

        // Attempt to update the Admin data in the database
        try {
            $response = $this->common->updatedatamodel("Admins", $post['id'], $post);
        } catch (Exception $e) {
            // Catch database update errors
            $errormsg = 'Error updating admin data in the database: ' . $e->getMessage();
            $this->session->set_flashdata('warningmessage', $errormsg);
            redirect(base_url('admin'));
            return;
        }

        // If update is successful, redirect with a success message
        if ($response) {
            $this->session->set_flashdata('successmessage', 'Admin user updated successfully');
            redirect(base_url('admin'));
        } else {
            // Handle case where update fails but no exception was thrown
            $errormsg = 'Error! Admin data cannot be updated.';
            $this->session->set_flashdata('warningmessage', $errormsg);
            redirect(base_url('admin'));
        }
    } catch (Exception $e) {
        // Catch any unexpected errors
        $errormsg = 'Unexpected error occurred: ' . $e->getMessage();
        $this->session->set_flashdata('warningmessage', $errormsg);
        redirect(base_url('admin'));
    }
}

public function deleteAdmin()
{
    try {
        // Get the admin ID from the URI segment
        $id = $this->uri->segment(3);

        // Initialize Firebase
        $firebase = $this->firebase->init();
        $auth = $firebase->createAuth();

        // Attempt to delete the user from Firebase
        try {
            $auth->deleteUser($id);
        } catch (Exception $e) {
            // Catch Firebase delete errors
            $errormsg = 'Error deleting user from Firebase: ' . $e->getMessage();
            $this->session->set_flashdata('warningmessage', $errormsg);
            redirect(base_url().'admin');
            return;
        }

        // Attempt to delete the admin data from the local database
        try {
            $response = $this->common->deletedatamodel('Admins', $id);
        } catch (Exception $e) {
            // Catch database delete errors
            $errormsg = 'Error deleting admin from the database: ' . $e->getMessage();
            $this->session->set_flashdata('warningmessage', $errormsg);
            redirect(base_url().'admin');
            return;
        }

        // If database deletion is successful
        if (!$response) {
            $this->session->set_flashdata('warningmessage', 'Something went wrong while deleting admin.');
        } else {
            // Success message
            $this->session->set_flashdata('successmessage', 'Admin Deleted');
        }

        // Redirect to the admin list page
        redirect(base_url().'admin');
    } catch (Exception $e) {
        // Catch any unexpected errors
        $errormsg = 'Unexpected error occurred: ' . $e->getMessage();
        $this->session->set_flashdata('warningmessage', $errormsg);
        redirect(base_url().'admin');
    }
}

	
	public function suspendCustomer()
	{
		$id = $this->uri->segment(3);
		$data["isActive"] = false;
		$this->common->updatedatamodel("Users", $id, $data);
		$this->session->set_flashdata('successmessage', 'Admin Suspended');
		redirect(base_url().'admin');
	}

	public function unSuspendCustomer()
	{
		$id = $this->uri->segment(3);
		
		$data["isActive"] = true;
		$this->common->updatedatamodel("Users", $id, $data);
		$this->session->set_flashdata('successmessage', 'Admin Activated');
		redirect(base_url().'admin');
	}
}