<?php

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

class Referrallist extends CI_Controller {

    public function __construct(){

        parent::__construct();

        $this->load->model('Referral_model');
        $this->load->helper(['form', 'url']);
    }


    public function index(){

        $data['referrals'] = $this->Referral_model->getAllReferrals();
        $data['companies'] = $this->Referral_model->getCompaniesForDropdown();
        $data['view'] = 'referral_list';

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


    // AJAX: called from the modal Submit button (status update only)
    public function saveReferral(){

        // echo $userId = $_COOKIE['userId']; die;
        echo "ssss"; die;

        $post = $this->input->post();

        $referralId = !empty($post['referralId']) ? (int)$post['referralId'] : 0;
        $refStatus  = trim($post['status'] ?? '');

        if($referralId <= 0){
            echo json_encode(['status' => false, 'message' => 'Invalid referral.']);
            exit;
        }

        if($refStatus === ''){
            echo json_encode(['status' => false, 'message' => 'Status is required.']);
            exit;
        }

      
        $row = [
            'referralStatus' => ($refStatus === 'Completed') ? 1 : 0,
            'statusUpdatedBy' => $userId,
        ];

        $this->Referral_model->updateReferral($referralId, $row);

        echo json_encode(['status' => true, 'message' => 'Referral status updated successfully.']);
        exit;
    }


    // AJAX: called from the Edit button, returns one row as JSON
    public function getReferral(){

        $id = $this->input->post('id');

        $referral = $this->Referral_model->getReferralById($id);

        echo json_encode($referral);
    }


    // Called from the Delete link
    public function deleteReferral($id){

        $this->Referral_model->deleteReferral($id);

        // Redirect to new URL path
        redirect('Referrallist/Referrallist');
    }

}