<?php session_start();

class LeadController {
    
    private $con;

	function __construct() {
		include_once("../../includes/DB/Connection.php");
		$db = new Connection();
		$this->con = $db->connect();
	}

    public function viewAllLeadsByCounselor($request){

        $logged_user_id = $_SESSION['log_session']['user_id']; // counselor
        $user_role_id = 4; // Counselor

        $sql_viewAllLeadsByCounselor = $this->con->query("SELECT 
            l.lead_id,
            CONCAT(l.lead_first_name, ' ', l.lead_last_name) AS lead_name,
            l.lead_phone_1,
            l.lead_email,
            l.lead_source,
            cam.campus_name,
            CONCAT(l.lead_created_date, ' ', l.lead_created_time) AS lead_created_date_time,
            (SELECT IFNULL(n.note_description, '')
                FROM note n
                WHERE n.lead_id = l.lead_id
                ORDER BY n.note_id DESC
                LIMIT 1) AS latest_note_description,
            l.lead_status
        FROM lead l
            INNER JOIN campus cam ON l.campus_id = cam.campus_id
            INNER JOIN branch bran ON l.branch_id = bran.branch_id
            INNER JOIN user u ON l.user_id = u.user_id
            INNER JOIN user_role ur ON u.user_role_id = ur.user_role_id
            WHERE u.user_id = '$logged_user_id' AND u.user_role_id = '$user_role_id' AND l.lead_status <= 6
            ORDER BY l.lead_id DESC");

        $data = [];
        if($sql_viewAllLeadsByCounselor->num_rows > 0){

            while($row = $sql_viewAllLeadsByCounselor->fetch_assoc()){
                $data[] = $row;
            }

            return ['status' => 1, 'message' => $data];

        }else{
            return ['status' => 0, 'message' => 'No data available!'];
        }

    }

    public function viewLead($request){
        
        if(isset($request['lead_id']) && !empty($request['lead_id'])){

            $lead_id = trim($request['lead_id']);
            $logged_user_id = $_SESSION['log_session']['user_id'];
            $logged_user_role_id = $_SESSION['log_session']['user_role_id'];
            $logged_user_camp_id = $_SESSION['log_session']['campus_id'];
            $logged_user_bran_id = $_SESSION['log_session']['branch_id'];

            $sql_viewLead = $this->con->query("SELECT 
                l.lead_id,
                l.lead_first_name,
                l.lead_last_name,
                l.lead_phone_1,
                l.lead_phone_2,
                l.lead_email,
                l.lead_address,
                l.lead_source,
                l.lead_pref_lang,
                cam.campus_name,
                bran.branch_name,
                CONCAT(u.user_first_name, ' ', u.user_last_name) AS assigned_counselor_name,
                CONCAT(l.lead_created_date, ' ', l.lead_created_time) AS lead_created_date_time,
                CONCAT(l.lead_updated_date, ' ', l.lead_updated_time) AS lead_updated_date_time,
                (SELECT IFNULL(CONCAT('[',GROUP_CONCAT(JSON_OBJECT('note_id', n.note_id, 'note_description', n.note_description, 'note_created_date_time', CONCAT(n.note_created_date, ' ', n.note_created_time))),']'),'[]')
                    FROM note n
                    WHERE n.lead_id = l.lead_id) AS all_notes,
                l.lead_status
            FROM lead l
                INNER JOIN campus cam ON l.campus_id = cam.campus_id
                INNER JOIN branch bran ON l.branch_id = bran.branch_id
                INNER JOIN user u ON l.user_id = u.user_id
                INNER JOIN user_role ur ON u.user_role_id = ur.user_role_id
                WHERE u.user_id = '$logged_user_id' 
                    AND u.user_role_id = '$logged_user_role_id'
                    AND l.campus_id = '$logged_user_camp_id'
                    AND l.branch_id = '$logged_user_bran_id'
                    AND l.lead_id = '$lead_id'
                    AND l.lead_status <= 6
                ORDER BY l.lead_id DESC");

            $data = [];
            if($sql_viewLead->num_rows > 0){

                while($row = $sql_viewLead->fetch_assoc()){
                    $data[] = $row;
                }

                return ['status' => 1, 'message' => $data];

            }else{
                return ['status' => 0, 'message' => 'No data available!'];
            }
        }
    }

    public function updateLead($request){

        if(!empty($request['lead_id'])){

            if(!empty($request['entered_lead_note'])){

                $logged_user_id = $_SESSION['log_session']['user_id']; // counselor

                $lead_id = trim($request['lead_id']);
                $lead_email = trim($request['lead_email']);
                $lead_status_id = trim($request['selected_lead_status']);
                $lead_note = trim($request['entered_lead_note']);

                date_default_timezone_set('Asia/Colombo');
                $server_date = date("Y-m-d");
                $server_time = date("H:i:s");

                // Perform the update query to activate the member
                $sql_update_lead = $this->con->query("UPDATE lead SET lead_email = '$lead_email', lead_status = '$lead_status_id', lead_updated_date = '$server_date', lead_updated_time = '$server_time' WHERE lead_id = '$lead_id' AND user_id = '$logged_user_id'");

                if($sql_update_lead){

                    // Check the number of affected rows
                    $affected_rows = $this->con->affected_rows;

                    if ($affected_rows > 0) {

                        // Prepare and bind parameters for the insert query
                        $stmt_add_lead_note = $this->con->prepare("INSERT INTO note (note_description, note_created_date, note_created_time, note_updated_date, note_updated_time, lead_id) VALUES (?, ?, ?, ?, ?, ?)");
                        $stmt_add_lead_note->bind_param("ssssss", $lead_note, $server_date, $server_time, $server_date, $server_time, $lead_id);

                        // Execute the insert query
                        $stmt_add_lead_note->execute();

                        // Check if the insert was successful
                        if($stmt_add_lead_note->affected_rows > 0) {
                            return ['status' => 1, 'message' => 'Lead Updated Successfully'];
                        } else {
                            return ['status' => 0, 'message' => 'Failed to add lead note!'];
                        }
                        

                    }else{
                        // No rows were updated / warning
                        return ['status' => 0, 'message' => 'Not updated. No matching rows found for updation!'];
                    }


                }else{
                    // The query failed / error
                    return ['status' => 0, 'message' => 'Failed to update lead!'];
                }

            }else{
                return ['status' => 0, 'message' => 'Please add a note!'];
            }

        }else{
            return ['status' => 0, 'message' => 'Invalid Request. Please Try Again!'];

        }

    }

    public function getLeadStatus($request){
        return $request;
    }

 

}

if (isset($_GET['VIEW_ALL_LEADS_BY_COUNSELOR'])) {
    if (isset($_SESSION['log_session']['user_id'])) {
        $lc = new LeadController();
        echo json_encode($lc->viewAllLeadsByCounselor($_GET));
		exit();
    }
}

if (isset($_GET['VIEW_LEAD'])) {
    if (isset($_SESSION['log_session']['user_id'])) {
        $lc = new LeadController();
        echo json_encode($lc->viewLead($_GET));
		exit();
    }
}

if (isset($_POST['UPDATE_LEAD'])) {
    if (isset($_SESSION['log_session']['user_id'])) {
        $lc = new LeadController();
        echo json_encode($lc->updateLead($_POST));
		exit();
    }
}




?>