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

class Analyticscontroller extends CI_Controller {

	public function __construct() {
        parent::__construct();
        date_default_timezone_set("Asia/Kolkata");
        $this->load->model('Analyticsmodel');
    }

	public function index() {
		if(!$this->session->userdata('is_logged_in') || $this->session->userdata('role') != 'Admin') {
	        redirect(base_url('login'));
	    }

	    $data['page_title'] = 'Advanced Analytics';
	    
	    $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;

	    // Fetch filters data
	    $data['branches'] = $this->db->where('status', 'Active')->get('tbl_branches')->result();
	    $data['products'] = $this->db->where('status', 'Active')->get('tbl_products')->result();

	    // 20. Executive KPI Cards
	    $data['kpis'] = $this->Analyticsmodel->getExecutiveKPIs($branch_id, $executive_id);

	    // 1. Lead Funnel Analysis
	    $data['funnel_data'] = $this->Analyticsmodel->getLeadFunnel($branch_id, $executive_id);

	    // 2. Product-wise Lead Distribution
	    $data['product_distribution'] = $this->Analyticsmodel->getProductDistribution($branch_id, $executive_id);

	    // 3. Product-wise Conversion Rate
	    $data['product_conversion'] = $this->Analyticsmodel->getProductConversionRate($branch_id, $executive_id);

	    // 4. Branch-wise Lead Performance
	    $data['branch_performance'] = $this->Analyticsmodel->getBranchPerformance($branch_id, $executive_id);

	    // 5. Monthly Lead Trend
	    $data['monthly_trend'] = $this->Analyticsmodel->getMonthlyLeadTrend($branch_id, $executive_id);

	    // 9. Upcoming Follow-up Dashboard
	    $data['followup_data'] = $this->Analyticsmodel->getFollowupDashboard($branch_id, $executive_id);

	    // 11. Lead Status Distribution
	    $data['status_distribution'] = $this->Analyticsmodel->getLeadStatusDistribution($branch_id, $executive_id);

	    $this->load->view('analytics', $data);
	}

	public function fetch_chart_data() {
		if(!$this->session->userdata('is_logged_in') || $this->session->userdata('role') != 'Admin') {
	        echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
			return;
	    }

	    $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;

		$chart_type = $this->input->post('chart_type');
		$date_range = $this->input->post('date_range') ?: 'default';

		$response = [];

		if ($chart_type == 'funnel') {
			$data = $this->Analyticsmodel->getLeadFunnel($branch_id, $executive_id, $date_range);
			$response = [
				'labels' => array_column($data, 'stage'),
				'series' => array_map('intval', array_column($data, 'count'))
			];
		} elseif ($chart_type == 'monthly_trend') {
			$data = $this->Analyticsmodel->getMonthlyLeadTrend($branch_id, $executive_id, $date_range);
			$response = [
				'labels' => array_column($data, 'month_year'),
				'series' => [
					array_map('intval', array_column($data, 'generated')),
					array_map('intval', array_column($data, 'converted')),
					array_map('intval', array_column($data, 'lost'))
				]
			];
		} elseif ($chart_type == 'product_dist') {
			$data = $this->Analyticsmodel->getProductDistribution($branch_id, $executive_id, $date_range);
			$labels = [];
			foreach($data as $item) { $labels[] = $item->product_name ?: 'Unknown'; }
			$response = [
				'labels' => $labels,
				'series' => array_map('intval', array_column($data, 'count'))
			];
		} elseif ($chart_type == 'status_dist') {
			$data = $this->Analyticsmodel->getLeadStatusDistribution($branch_id, $executive_id, $date_range);
			$response = [
				'labels' => array_column($data, 'lead_status'),
				'series' => array_map('intval', array_column($data, 'count'))
			];
		} elseif ($chart_type == 'followup') {
			$data = $this->Analyticsmodel->getFollowupDashboard($branch_id, $executive_id, $date_range);
			$response = [
				'series' => [
					intval($data->overdue),
					intval($data->today),
					intval($data->tomorrow),
					intval($data->next_3_days),
					intval($data->next_7_days)
				]
			];
		} elseif ($chart_type == 'product_conv') {
			$data = $this->Analyticsmodel->getProductConversionRate($branch_id, $executive_id, $date_range);
			$labels = [];
			foreach($data as $item) { $labels[] = $item->product_name ?: 'Unknown'; }
			$response = [
				'labels' => $labels,
				'series' => [
					array_map('intval', array_column($data, 'total_leads')),
					array_map('intval', array_column($data, 'converted_leads'))
				]
			];
		} elseif ($chart_type == 'branch_perf') {
			$data = $this->Analyticsmodel->getBranchPerformance($branch_id, $executive_id, $date_range);
			$labels = [];
			foreach($data as $item) { $labels[] = $item->branch_name ?: 'Unknown'; }
			$response = [
				'labels' => $labels,
				'series' => [
					array_map('intval', array_column($data, 'total_leads')),
					array_map('intval', array_column($data, 'converted_leads'))
				]
			];
		}

		echo json_encode($response);
	}
}
