<?php

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

class Leadcontroller extends CI_Controller {
    public function __construct() {
        parent::__construct();
        date_default_timezone_set("Asia/Kolkata");
        // Check if user is logged in
        if(!$this->session->userdata('is_logged_in')) {
            redirect(base_url('login'));
        }
        if($this->session->userdata('role') == 'Super Admin') {
            redirect(base_url('users'));
        }
        $this->load->model('Leadmodel');
        $this->load->library('form_validation');
    }
    // List all leads
    public function index() {
        $data['page_title'] = 'Lead Management';
        $filters = array();

        if ($this->session->userdata('role') == 'Executive') {
            $filters['executive_id'] = $this->session->userdata('admin_id');
        } elseif ($this->session->userdata('role') == 'Branch Manager') {
            $filters['branch_id'] = $this->session->userdata('branch_id');
        } elseif ($this->session->userdata('role') == 'ABM') {
            $filters['branch_id'] = $this->session->userdata('branch_id');
        } elseif ($this->session->userdata('role') == 'Clerk') {
            $filters['branch_id'] = $this->session->userdata('branch_id');
        } elseif ($this->session->userdata('role') == 'Probationary Clerk') {
            $filters['branch_id'] = $this->session->userdata('branch_id');
        } elseif ($this->session->userdata('role') == 'Trainee Clerk') {
            $filters['branch_id'] = $this->session->userdata('branch_id');
        }
        // Status Filter
        if ($this->input->get('status')) {
            $filters['lead_status'] = $this->input->get('status');
        }
        // Branch Filter
        if ($this->input->get('branch')) {
            $filters['branch_id'] = $this->input->get('branch');
        }
        // Product Filter
        if ($this->input->get('product')) {
            $filters['product_id'] = $this->input->get('product');
        }
        // Search Filter
        if ($this->input->get('search')) {
            $filters['search'] = $this->input->get('search');
        }
        $data['leads'] = $this->Leadmodel->getLeads($filters);
        $data['products'] = $this->Leadmodel->getProducts();
        $data['branches'] = $this->Leadmodel->getBranches();

        $this->load->view('leads/list', $data);
    }
    // Add new lead
    public function add() {
    	//echo '<pre>'; print_r($_POST); EXIT;
        $data['page_title'] = 'Add New Lead';
        $data['branches'] = $this->Leadmodel->getBranches();
        $data['executives'] = $this->Leadmodel->getRoles();
        $data['categories'] = $this->Leadmodel->getProductsCategory();
        // $data['products'] = $this->Leadmodel->getProducts();
        $data['products'] = array();
        
        if ($this->input->post()) {
            //echo '<pre>'; print_r($_POST); EXIT;
            $this->form_validation->set_rules('customer_name', 'Customer Name', 'required|trim');
            $this->form_validation->set_rules('customer_mobile', 'Mobile Number', 'required|trim|numeric|exact_length[10]');
            $this->form_validation->set_rules('product_id', 'Product', 'required');
            $this->form_validation->set_rules('is_existing_customer', 'Customer Type', 'required');
            
            if ($this->form_validation->run() == TRUE) {
                $mobile = $this->input->post('customer_mobile');
                $duplicate = $this->Leadmodel->checkDuplicateLead($mobile);
                if ($duplicate) {
                    // echo 'duplicate Number';EXIT;
                    $this->session->set_flashdata('error', 'Mobile number already exists.');
                    redirect(base_url('leads/add'), 'refresh');
                    exit;
                }
                $role = $this->session->userdata('role');
                //echo $role;EXIT;
                if ($role == 'Admin' || $role == 'Super Admin') {
                    $branch_id = $this->input->post('branch_id');
                    $executive_id = $this->input->post('admin_id');
                } elseif ($role == 'ABM' || $role == 'Branch Manager' || $role == 'Clerk' || $role == 'Probationary Clerk' || $role == 'Trainee Clerk') {
                    $branch_id = $this->session->userdata('branch_id');
                    $executive_id = $this->session->userdata('admin_id');
                }
                // Prepare lead data
                $lead_data = array(
                    'branch_id' => $branch_id,
                    'executive_id' => $executive_id,
                    'customer_name' => $this->input->post('customer_name'),
                    'customer_email' => $this->input->post('customer_email'),
                    'customer_mobile' => $this->input->post('customer_mobile'),
                    'customer_alter_mobile' => $this->input->post('customer_alter_mobile'),
                    'customer_dob' => $this->input->post('customer_dob'),
                    'customer_gender' => $this->input->post('customer_gender'),
                    'customer_city' => $this->input->post('customer_city'),
                    'customer_area' => $this->input->post('customer_area'),
                    'customer_state' => $this->input->post('customer_state'),
                    'customer_pincode' => $this->input->post('customer_pincode'),
                    'customer_type' => $this->input->post('customer_type'),
                    'customer_occupation_type' => $this->input->post('customer_occupation_type'),
                    'customer_employer_business_name' => $this->input->post('customer_employer_business_name'),
                    'customer_monthly_annual_income' => $this->input->post('customer_monthly_annual_income'),
                    'is_existing_customer' => $this->input->post('is_existing_customer'),
                    'account_number' => $this->input->post('account_number'),
                    'relationship_number' => $this->input->post('relationship_number'),
                    'category_id' => $this->input->post('category_id'),
                    'product_id' => $this->input->post('product_id'),
                    'lead_status' => 'New Lead',
                    'next_followup_date' => $this->input->post('next_followup_date'),
                    'customer_lead_source_type' => $this->input->post('customer_lead_source_type'),
                    'customer_lead_source_channel' => $this->input->post('customer_lead_source_channel'),
                    'customer_lead_campaign_name' => $this->input->post('customer_lead_campaign_name'),
                    'customer_lead_referrer_detail' => $this->input->post('customer_lead_referrer_detail'),
                    'lead_type' => 'Manual'
                ); 
                // Prepare product-specific data
                $product_data = array(
                    'category_id' => $this->input->post('category_id'),
                    'product_id' => $this->input->post('product_id'),
                    'remarks' => $this->input->post('remarks')
                );
                // Add product-specific fields based on product type
                $product_id = $this->input->post('product_id');
                if ($product_id == 1) { // Home Loans
                    $product_data['property_value'] = $this->input->post('property_value');
                    $product_data['loan_amount'] = $this->input->post('loan_amount');
                    $product_data['income_source'] = $this->input->post('income_source');
                    $product_data['expected_purchase_month'] = $this->input->post('expected_purchase_month');
                    $product_data['expected_purchase_year'] = $this->input->post('expected_purchase_year');
                    $product_data['property_identified'] = $this->input->post('property_identified');
                    $product_data['property_address'] = $this->input->post('property_address');
                } elseif ($product_id == 2) { // Car Loans
                    $product_data['car_value'] = $this->input->post('car_value');
                    $product_data['car_make'] = $this->input->post('car_make');
                    $product_data['car_grade'] = $this->input->post('car_grade');
                    $product_data['loan_amount'] = $this->input->post('loan_amount');
                    $product_data['income_source'] = $this->input->post('income_source');
                    $product_data['expected_purchase_month'] = $this->input->post('expected_purchase_month');
                    $product_data['expected_purchase_year'] = $this->input->post('expected_purchase_year');
                } elseif ($product_id == 3) { // Two Wheeler Loans
                    $product_data['two_wheeler_value'] = $this->input->post('two_wheeler_value');
                    $product_data['two_wheeler_make'] = $this->input->post('two_wheeler_make');
                    $product_data['two_wheeler_grade'] = $this->input->post('two_wheeler_grade');
                    $product_data['loan_amount'] = $this->input->post('loan_amount');
                    $product_data['income_source'] = $this->input->post('income_source');
                    $product_data['expected_purchase_month'] = $this->input->post('expected_purchase_month');
                    $product_data['expected_purchase_year'] = $this->input->post('expected_purchase_year');
                } elseif ($product_id == 4 || $product_id == 12 || $product_id == 13 || $product_id == 14) { // Fixed Deposits
                    $product_data['deposit_amount'] = $this->input->post('deposit_amount');
                    $product_data['tenure_days'] = $this->input->post('tenure_days');
                    $product_data['interest_rate'] = $this->input->post('interest_rate');
                    $product_data['maturity_value'] = $this->input->post('maturity_value');
                    $product_data['creation_month'] = $this->input->post('creation_month');
                    $product_data['creation_year'] = $this->input->post('creation_year');
                } elseif ($product_id == 5 || $product_id == 11) { // Savings Account
                    $product_data['account_creation_month'] = $this->input->post('account_creation_month');
                    $product_data['account_creation_year'] = $this->input->post('account_creation_year');
                } elseif ($product_id == 6) { // MSME Loan
                    $product_data['msme_business_name'] = $this->input->post('msme_business_name');
                    $product_data['msme_business_type'] = $this->input->post('msme_business_type');
                    $product_data['msme_business_vintage'] = $this->input->post('msme_business_vintage');
                    $product_data['msme_business_annual_turnover'] = $this->input->post('msme_business_annual_turnover');
                    $product_data['msme_business_loan_amount'] = $this->input->post('msme_business_loan_amount');
                    $product_data['msme_business_loan_purpose'] = $this->input->post('msme_business_loan_purpose');
                } elseif ($product_id == 7) { // Education Loan
                    $product_data['course_name'] = $this->input->post('course_name');
                    $product_data['college_name'] = $this->input->post('college_name');
                    $product_data['study_location'] = $this->input->post('study_location');
                    $product_data['course_fee'] = $this->input->post('course_fee');
                    $product_data['course_loan_amount'] = $this->input->post('course_loan_amount');
                } elseif ($product_id == 8) { // Mortgage Loan
                    $product_data['mortgage_property_type'] = $this->input->post('mortgage_property_type');
                    $product_data['mortgage_property_value'] = $this->input->post('mortgage_property_value');
                    $product_data['mortgage_property_location'] = $this->input->post('mortgage_property_location');
                    $product_data['mortgage_loan_amount'] = $this->input->post('mortgage_loan_amount');
                    $product_data['mortgage_income_source'] = $this->input->post('mortgage_income_source');
                    $product_data['mortgage_loan_purpose'] = $this->input->post('mortgage_loan_purpose');
                } 
                // Create lead
                $lead_id = $this->Leadmodel->createLead($lead_data, $product_data);
                if ($lead_id) {
                    $this->session->set_flashdata('success', 'Lead created successfully!');
                    redirect(base_url('leads/view/' . $lead_id), 'refresh');
                    exit;
                } else {
                    $this->session->set_flashdata('error', 'Failed to create lead. Please try again.');
                    redirect(base_url('leads/add'), 'refresh');
                    exit;
                }
            }
        }
        $this->load->view('leads/add', $data);
    }
    // AJAX Method: Get Products by Category
    public function getProductsByCategory() {
        $category_id = $this->input->post('category_id');

        if (!empty($category_id)) {
            $products = $this->Leadmodel->getProductsByCategory($category_id);
            echo json_encode($products);
        } else {
            echo json_encode(array());
        }
    }
    // View lead details
    public function view($lead_id) {
        $data['page_title'] = 'Lead Details';
        $data['lead'] = $this->Leadmodel->getLeadById($lead_id);
        if (!$data['lead']) {
            show_404();
        }
        // Check access permission
        if ($this->session->userdata('role') == 'Executive' && 
            $data['lead']->executive_id != $this->session->userdata('admin_id')) {
            show_error('You do not have permission to view this lead.');
        }
        $data['followups'] = $this->Leadmodel->getLeadFollowups($lead_id);
        $this->load->view('leads/view', $data);
    }
    // Add follow-up
    public function followup($lead_id) {
        $data['page_title'] = 'Add Follow-up';
        $data['lead'] = $this->Leadmodel->getLeadById($lead_id);
        if (!$data['lead']) {
            show_404();
        }
        // Check access permission
        if ($this->session->userdata('role') == 'Executive' && 
            $data['lead']->executive_id != $this->session->userdata('admin_id')) {
            show_error('You do not have permission to update this lead.');
        }
        if ($this->input->post()) {
            $this->form_validation->set_rules('updated_status', 'Status', 'required');
            $this->form_validation->set_rules('lead_priority', 'Priority', 'required');
            $this->form_validation->set_rules('followup_notes', 'Follow-up Notes', 'required|trim');
            
            if ($this->form_validation->run() == TRUE) {
                $followup_data = array(
                    'lead_id' => $lead_id,
                    'followup_by' => $this->session->userdata('admin_id'),
                    'previous_status' => $data['lead']->lead_status,
                    'updated_status' => $this->input->post('updated_status'),
                    'lead_priority' => $this->input->post('lead_priority'),
                    'followup_notes' => $this->input->post('followup_notes'),
                    'next_followup_date' => $this->input->post('next_followup_date')
                );
                if ($this->Leadmodel->addFollowup($followup_data)) {
                    $this->session->set_flashdata('success', 'Follow-up added successfully!');
                    redirect(base_url('leads/view/' . $lead_id), 'refresh');
                    exit;
                } else {
                    $this->session->set_flashdata('error', 'Failed to add follow-up. Please try again.');
                    redirect(base_url('leads/followup/' . $lead_id), 'refresh');
                    exit;
                }
            }
        }
        $this->load->view('leads/followup', $data);
    }
    // Edit lead
    public function edit($lead_id) {
        $data['page_title'] = 'Edit Lead';
        $data['branches'] = $this->Leadmodel->getBranches();
        $data['executives'] = $this->Leadmodel->getRoles();
        $data['lead'] = $this->Leadmodel->getLeadById($lead_id);
        $data['products'] = $this->Leadmodel->getProducts();
        if (!$data['lead']) {
            show_404();
        }
        // Check access permission
        if ($this->session->userdata('role') == 'Executive' && 
            $data['lead']->executive_id != $this->session->userdata('admin_id')) {
            show_error('You do not have permission to edit this lead.');
        }
        if ($this->input->post()) {
            $this->form_validation->set_rules('customer_name', 'Customer Name', 'required|trim');
            $this->form_validation->set_rules('customer_mobile', 'Mobile Number', 'required|trim|numeric|exact_length[10]');
            if ($this->form_validation->run() == TRUE) {
                $role = $this->session->userdata('role');
                if ($role == 'Admin' || $role == 'Super Admin') {
                    $branch_id = $this->input->post('branch_id');
                    $executive_id = $this->input->post('admin_id');
                } elseif ($role == 'ABM' || $role == 'Branch Manager' || $role == 'Clerk' || $role == 'Probationary Clerk' || $role == 'Trainee Clerk') {
                    $branch_id = $this->session->userdata('branch_id');
                    $executive_id = $this->session->userdata('admin_id');
                }
                $lead_data = array(
                    'branch_id' => $branch_id,
                    'executive_id' => $executive_id,
                    'customer_name' => $this->input->post('customer_name'),
                    'customer_email' => $this->input->post('customer_email'),
                    'customer_mobile' => $this->input->post('customer_mobile'),
                    'customer_mobile' => $this->input->post('customer_mobile'),
                    'customer_alter_mobile' => $this->input->post('customer_alter_mobile'),
                    'customer_dob' => $this->input->post('customer_dob'),
                    'customer_gender' => $this->input->post('customer_gender'),
                    'customer_city' => $this->input->post('customer_city'),
                    'customer_area' => $this->input->post('customer_area'),
                    'customer_state' => $this->input->post('customer_state'),
                    'customer_pincode' => $this->input->post('customer_pincode'),
                    'customer_type' => $this->input->post('customer_type'),
                    'customer_occupation_type' => $this->input->post('customer_occupation_type'),
                    'customer_employer_business_name' => $this->input->post('customer_employer_business_name'),
                    'customer_monthly_annual_income' => $this->input->post('customer_monthly_annual_income'),
                    'is_existing_customer' => $this->input->post('is_existing_customer'),
                    'account_number' => $this->input->post('account_number'),
                    'relationship_number' => $this->input->post('relationship_number')
                );
                if ($this->Leadmodel->updateLead($lead_id, $lead_data)) {
                    $this->session->set_flashdata('success', 'Lead updated successfully!');
                    redirect(base_url('leads/view/' . $lead_id), 'refresh');
                    exit;
                } else {
                    $this->session->set_flashdata('error', 'Failed to update lead. Please try again.');
                    redirect(base_url('leads/edit/' . $lead_id), 'refresh');
                    exit;
                }
            }
        }
        $this->load->view('leads/edit', $data);
    }
    // Delete lead
    public function delete($lead_id) {
        // Only Admin can delete
        if ($this->session->userdata('role') != 'Admin' && $this->session->userdata('role') != 'Super Admin') {
            show_error('You do not have permission to delete leads.');
        }
        if ($this->Leadmodel->deleteLead($lead_id)) {
            $this->session->set_flashdata('success', 'Lead deleted successfully!');
        } else {
            $this->session->set_flashdata('error', 'Failed to delete lead.');
        }
        redirect(base_url('leads'));
    }
    // Get lead statistics (AJAX)
    public function statistics() {
        $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;
        $stats = $this->Leadmodel->getLeadStatistics($branch_id, $executive_id);
        $product_stats = $this->Leadmodel->getProductStatistics($branch_id, $executive_id);
        echo json_encode(array(
            'status' => 'success',
            'lead_stats' => $stats,
            'product_stats' => $product_stats
        ));
    }
}
