<?php


class followup_controller extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('followup_model');
    }

  

    /* ===============================
       WEEKLY VIEW
    ================================ */
  public function weekly_followups()
   {
    header('Content-Type: application/json');

    try {

        $data = $this->followup_model->get_pending_followups();

        echo json_encode([
            'status' => true,
            'count'  => count($data),
            'data'   => $data
        ]);

    } catch (Exception $e) {

        log_message('error', 'Weekly Followups Error: '.$e->getMessage());

        echo json_encode([
            'status'  => false,
            'message' => 'Something went wrong'
        ]);
    }
}


    /* ===============================
       ALL ENROLLED
    ================================ */
    public function enrolled_children_get()
    {
        $data = $this->followup_model->get_all_enrolled();
        $this->response(['status'=>true,'data'=>$data],200);
    }

    /* ===============================
       SAVE FOLLOWUP ATTEMPT
    ================================ */
   public function save_followup()
   {
    header('Content-Type: application/json');

    $input = json_decode(file_get_contents('php://input'), true);

    if(empty($input['followups'])){
        echo json_encode([
            'status'=>false,
            'message'=>'No data received'
        ]);
        return;
    }

    $success = [];
    $failed = [];

    foreach($input['followups'] as $row)
    {
        $followup_id = $row['followup_id'] ?? null;
        $visit_status = $row['visit_status'] ?? null;
        $outcome = $row['outcome'] ?? null;
        $remarks = $row['remarks'] ?? null;

        if(!$followup_id || !$visit_status){
            $failed[] = $row;
            continue;
        }

        $result = $this->followup_model->save_attempt_new(
            $followup_id,
            $visit_status,
            $outcome,
            $remarks
        );

        if($result){
            $success[] = $followup_id;
        } else {
            $failed[] = $row;
        }
    }

    echo json_encode([
        'status'=>true,
        'updated_count'=>count($success),
        'failed_count'=>count($failed),
        'updated_ids'=>$success,
        'failed_records'=>$failed
    ]);
}



    /* ===============================
       CHILD COLOR STATUS
    ================================ */
    public function child_status_get($child_id)
    {
        $color = $this->followup_model->get_child_status_color($child_id);
        $this->response(['status'=>true,'color'=>$color],200);
    }
}
