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

class followup_model extends CI_Model {
 //put your code here
    var $mdb;
    var $vdb;

    public function __construct() {
        parent::__construct();
        $this->mdb = $this->load->database('mdb', TRUE);
       
    }
 

    /* ======================================
       GET WEEKLY FOLLOWUPS
    ======================================= */
/*  
    public function get_weekly_followups()
    {
        $start = date('Y-m-d');
        $end = date('Y-m-d', strtotime('+7 days'));

        $this->mdb->select('mira_child.child_name, followup_schedule.*');
        $this->mdb->from('followup_schedule');
        $this->mdb->join('mira_child','mira_child.child_id=followup_schedule.child_id');
        $this->mdb->where('followup_schedule.scheduled_date >=',$start);
        $this->mdb->where('followup_schedule.scheduled_date <=',$end);
        $this->mdb->where('followup_schedule.status','pending');

        return $this->mdb->get()->result();
    }

*/



    public function get_weekly_followups()
    {
    $start = date('Y-m-d 00:00:00');
    $end   = date('Y-m-d 23:59:59', strtotime('+7 days'));

    $this->mdb->select('mira_child.child_name,mira_child.actual_register_date, followup_schedule.*');
    $this->mdb->from('followup_schedule');
    $this->mdb->join('mira_child','mira_child.child_id = followup_schedule.child_id');

    $this->mdb->where('followup_schedule.completed_at >=', $start);
    $this->mdb->where('followup_schedule.completed_at <=', $end);
    $this->mdb->where('followup_schedule.status', 'done');

    return $this->mdb->get()->result();
}

    /* ======================================
       GET ALL ENROLLED CHILDREN
    ======================================= */
    public function get_all_enrolled()
    {
        return $this->mdb->get('children')->result();
    }

    /* ======================================
       SAVE FOLLOWUP ATTEMPT
    ======================================= */
    public function save_attempt($followup_id, $visit_status, $outcome=null, $remarks=null)
    {
        $followup = $this->mdb->get_where('followup_schedule',['id'=>$followup_id])->row();

        if(!$followup) return false;

        $attempt_number = $followup->attempt_count + 1;

        // insert attempt
        $this->mdb->insert('followup_attempts',[
            'followup_id'=>$followup_id,
            'attempt_number'=>$attempt_number,
            'visit_status'=>$visit_status,
            'outcome'=>$outcome,
            'remarks'=>$remarks
        ]);

        // update attempt count
        $this->mdb->where('id',$followup_id);
        $this->mdb->update('followup_schedule',[
            'attempt_count'=>$attempt_number
        ]);

        /* ===== LOGIC ===== */

        if($visit_status == 'done'){
            $this->mdb->where('id',$followup_id);
            $this->mdb->update('followup_schedule',[
                'status'=>'done',
                'completed_at'=>date('Y-m-d H:i:s')
            ]);
        }

        if($visit_status == 'not_available' && $attempt_number >= 2){
            $this->mdb->where('id',$followup_id);
            $this->mdb->update('followup_schedule',[
                'status'=>'missed'
            ]);
        }

        if($visit_status == 'not_available' && $attempt_number == 1){
            $this->mdb->where('id',$followup_id);
            $this->mdb->update('followup_schedule',[
                'status'=>'not_available'
            ]);
        }

        return true;
    }

    /* ======================================
       GET CHILD STATUS COLOR
    ======================================= */
    public function get_child_status_color($child_id)
    {
        $this->mdb->order_by('followup_number','DESC');
        $followup = $this->mdb->get_where('followup_schedule',['child_id'=>$child_id])->row();

        if(!$followup) return 'yellow';

        $attempt = $this->mdb->order_by('attempt_number','DESC')
                            ->get_where('followup_attempts',['followup_id'=>$followup->id])
                            ->row();

        if(!$attempt) return 'yellow';

        if($attempt->visit_status == 'not_available')
            return 'yellow';

        if($attempt->outcome == 'convinced')
            return 'green';

        if($attempt->outcome == 'refused')
            return 'red';

        if($followup->status == 'missed')
            return 'black';

        return 'yellow';
    }
    
    
    // new code
    public function get_pending_followups()
    {
     $today = date('Y-m-d');
    
    /* 
     // for testing purpose after 15 days 
     $now = date('Y-m-d H:i:s');
     $today =  date(
                'Y-m-d',
                strtotime($now . ' +15 days')
            );
     */
    $this->mdb->select('mira_child.child_name,
                        followup_schedule.*');
    $this->mdb->from('followup_schedule');
    $this->mdb->join('mira_child','mira_child.child_id = followup_schedule.child_id');

    $this->mdb->where_in('followup_schedule.status',['pending']);
    $this->mdb->where('followup_schedule.scheduled_date <=',$today);

    return $this->mdb->get()->result();
   }
   
    public function save_followup_attempt($followup_id, $visit_status, $outcome=null, $remarks=null)
    {
    $followup = $this->mdb->get_where('followup_schedule',['id'=>$followup_id])->row();

    if(!$followup) return false;

    $now = date('Y-m-d H:i:s');

    // Mark current followup as done
    if($visit_status == 'done'){

        $this->mdb->where('id',$followup_id);
        $this->mdb->update('followup_schedule',[
            'status' => 'done',
            'completed_at' => $now
        ]);

        // 🔥 Create next followup if not 3rd
        if($followup->followup_number < 6){

            $next_followup_number = $followup->followup_number + 1;

            $next_schedule_date = date(
                'Y-m-d',
                strtotime($now . ' +15 days')
            );

            $this->mdb->insert('followup_schedule',[
                'child_id' => $followup->child_id,
                'followup_number' => $next_followup_number,
                'scheduled_date' => $next_schedule_date,
                'status' => 'pending'
            ]);
        }

        return true;
    }

    // Not available logic
    if($visit_status == 'not_available'){
        $this->mdb->where('id',$followup_id);
        $this->mdb->update('followup_schedule',[
            'status'=>'not_available'
        ]);
        return true;
    }

    return false;
}

    public function save_attempt_new($followup_id, $visit_status, $outcome=null, $reason = null)
    {
    $followup = $this->mdb
                     ->get_where('followup_schedule', ['id'=>$followup_id])
                     ->row();

    if(!$followup){
        return false;
    }

    // Get current attempt count
    $attempt_count = $this->mdb
                          ->where('followup_id',$followup_id)
                          ->count_all_results('followup_attempts');

    // ❌ Max 2 attempts allowed
  /*  if($attempt_count >= 2){
        return ['status'=>false,'message'=>'Maximum attempts reached'];
    }
    */

    $attempt_number = $attempt_count + 1;

    // Save attempt
    $this->mdb->insert('followup_attempts',[
        'followup_id'   => $followup_id,
        'attempt_number'=> $attempt_number,
        'visit_status'  => $visit_status,
        'remarks'        => $reason,
        'outcome'=>$outcome,
        'created_at'    => date('Y-m-d H:i:s')
    ]);

    /* ==========================
       CASE 1: VISIT DONE
    ========================== */

    if($visit_status == 'done'){

        $now = date('Y-m-d H:i:s');

        // Update followup as completed
        $this->mdb->where('id',$followup_id);
        $this->mdb->update('followup_schedule',[
            'status'=>'done',
            'completed_at'=>$now,
            'attempt_count'=>$attempt_number
            
        ]);

        // Create next followup (if less than 3)
        if($followup->followup_number < 6){

            $next_number = $followup->followup_number + 1;

            $next_date = date('Y-m-d', strtotime($now.' +15 days'));

            $this->mdb->insert('followup_schedule',[
                'child_id' => $followup->child_id,
                'followup_number' => $next_number,
                'scheduled_date' => $next_date,
                'status' => 'pending'
            ]);
        }

        return ['status'=>true,'message'=>'Followup completed'];
    }

    /* ==========================
       CASE 2: NOT AVAILABLE
    ========================== */

    if($visit_status == 'not_available'){

       
          if($attempt_number == 1){

            $this->mdb->where('id',$followup_id);
            $this->mdb->update('followup_schedule',[
                'attempt_count'=>1
            ]);

            return ['status'=>true,'message'=>'Followup attempt_count is updated'];
        }
        // If second attempt also not available → mark missed
        if($attempt_number == 2){
            $now = date('Y-m-d H:i:s');
            $this->mdb->where('id',$followup_id);
            $this->mdb->update('followup_schedule',[
                'status'=>'missed',
                'attempt_count'=>2,
                'completed_at'=>$now
            ]);
             
            $next_number = $followup->followup_number + 1;
            
            $next_date = date('Y-m-d', strtotime($now.' +15 days'));

            $this->mdb->insert('followup_schedule',[
                'child_id' => $followup->child_id,
                'followup_number' => $next_number,
                'scheduled_date' => $next_date,
                'status' => 'pending'
            ]);
             
            return ['status'=>true,'message'=>'Followup marked as missed'];
        }

        return ['status'=>true,'message'=>'First attempt saved'];
    }

    return ['status'=>false,'message'=>'Invalid status'];
}



}
