<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Homecontroller extends CI_Controller {
	public function __construct() {
        parent::__construct();
        date_default_timezone_set("Asia/Kolkata");
        $this->load->model('Loginmodel');
        $this->load->model('Leadmodel');
        $this->load->library('form_validation');
    }
	public function index() {
		if(!$this->session->userdata('is_logged_in')) {
	        redirect(base_url('login'));
	    }
	    
	    $data['page_title'] = 'Dashboard';

	    if($this->session->userdata('role') == 'Super Admin') {
            $data['total_users'] = $this->db->count_all('tbl_admin');
            $data['active_users'] = $this->db->where('status', 'Active')->count_all_results('tbl_admin');
            $data['total_branches'] = $this->db->count_all('tbl_branches');
            $data['active_branches'] = $this->db->where('status', 'Active')->count_all_results('tbl_branches');
            
            $this->load->view('superadmin_dashboard', $data);
            return;
	    }
	    // Get statistics based on role
	    $branch_id = ($this->session->userdata('role') != 'Admin' && $this->session->userdata('role') != 'Super Admin') ? $this->session->userdata('branch_id') : null;
	    $executive_id = ($this->session->userdata('role') == 'Executive') ? $this->session->userdata('admin_id') : null;
	    $data['lead_stats'] = $this->Leadmodel->getLeadStatistics($branch_id, $executive_id);
	    $data['product_stats'] = $this->Leadmodel->getProductStatistics($branch_id, $executive_id);
	    $data['branch_stats'] = $this->Leadmodel->getBranchStatistics($branch_id, $executive_id);
	    // $data['branch_mis_stats'] = $this->Leadmodel->getBranchMISStatistics($branch_id, $executive_id);
	    $data['branch_product_mis_stats'] = $this->Leadmodel->getBranchProductMISStatistics($branch_id, $executive_id);
	    $data['upcoming_followups'] = $this->Leadmodel->getUpcomingFollowups($branch_id, $executive_id, 7);
	    $this->load->view('dashboard', $data);
	}
	public function login() {
		if($this->session->userdata('is_logged_in')) {
			redirect(base_url('index'));
		}
		$this->load->view('login');
	}
	public function loginProcess() {
        // echo '<pre>'; print_r($_POST); EXIT;
		if(isset($_POST) && !empty($_POST)) {
			if($this->Loginmodel->loginValidation()) {
				echo json_encode([
					'status' => 'success',
					'message' => 'Login Successfully!!!',
					'redirect' => base_url('/')
				]);
			} else {
				echo json_encode([
					'status' => 'error',
					'message' => 'Invalid Credentials.'
				]);
			}
		} else {
			echo json_encode([
				'status' => 'error',
				'message' => 'Invalid Request.'
			]);
		}
	}
	public function logout() {
		$this->session->sess_destroy();
		redirect(base_url('login'));
	}
	/*public function downloadBranchMIS() {
	    if(!$this->session->userdata('is_logged_in')) {
	        redirect(base_url('login'));
	    }
	    $branch_id = ($this->session->userdata('role') != 'Admin' && $this->session->userdata('role') != 'Super Admin') ? $this->session->userdata('branch_id') : null;
	    $executive_id = ($this->session->userdata('role') == 'Executive') ? $this->session->userdata('admin_id') : null;
	    $branch_stats = $this->Leadmodel->getBranchMISStatistics($branch_id, $executive_id);
	    header("Content-Type: text/csv");
	    header("Content-Disposition: attachment; filename=branch_mis_report.csv");
	    $output = fopen("php://output", "w");
	    // CSV Header
	    fputcsv($output, array(
	        'Sr. No',
	        'Branch Name',
	        'Total Leads',
	        'New Leads',
	        'Closed',
	        'Completed',
	        'Rejected'
	    ));
	    // CSV Data
	    $i = 1;
	    foreach ($branch_stats as $row) {
	        fputcsv($output, array(
	            $i++,
	            $row->branch_name,
	            $row->total_leads,
	            $row->new_leads,
	            $row->closed_leads,
	            $row->completed_leads,
	            $row->rejected_leads
	        ));
	    }
	    fclose($output);
	    exit;
	}*/
	public function downloadBranchProductMIS() {
	    if(!$this->session->userdata('is_logged_in')) {
	        redirect(base_url('login'));
	    }
	    $branch_id = ($this->session->userdata('role') != 'Admin' && $this->session->userdata('role') != 'Super Admin') ? $this->session->userdata('branch_id') : null;
	    $executive_id = ($this->session->userdata('role') == 'Executive') ? $this->session->userdata('admin_id') : null;
	    $records = $this->Leadmodel->getBranchProductMISStatistics($branch_id, $executive_id);
	    header("Content-Type: text/csv");
	    header("Content-Disposition: attachment; filename=branch_product_mis_report.csv");
	    $output = fopen("php://output", "w");
	    // CSV Header
	    fputcsv($output, array(
	        'Sr. No',
	        'Branch Name',
	        'Product Name',
	        'Total Leads',
	        'New Leads',
	        'Closed',
	        'Completed',
	        'Rejected'
	    ));
	    // CSV Data
	    $i = 1;
	    foreach ($records as $row) {
	        fputcsv($output, array(
	            $i++,
	            $row->branch_name,
	            $row->product_name,
	            $row->total_leads,
	            $row->new_leads,
	            $row->closed_leads,
	            $row->completed_leads,
	            $row->rejected_leads
	        ));
	    }
	    fclose($output);
	    exit;
	}
}