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

class Attendancemonthly extends CI_Controller {

    public function __construct()
    {
        parent::__construct();

        $this->load->database();
    }

    public function index()
    {
        $data = [
            "active_menu" => "attendance_monthly"
        ];

        $this->load->view('partials/header', $data);
        $this->load->view('employees/attendance_monthly');
        $this->load->view('partials/footer');
    }

    public function get_data()
    {
        $date = $this->input->get('date') . '-01';

        if(!$date){
            $date = date('Y-m-d');
        }

        $data = $this->db->query("
            SELECT
                a.*,
                e.employee_code,
                e.full_name
            FROM k_attendance_monthly a
            LEFT JOIN k_employees e ON e.id = a.employee_id
            WHERE a.month = '$date'
            ORDER BY a.updated_at DESC
        ")->result();

        $rows = [];
        $no = 1;

        foreach($data as $row){

            $rows[] = [
                $no++,
                $row->employee_code,
                $row->full_name,
                tanggal_indo($row->month,'F Y'),
                $row->status,
                '
                <button class="btn btn-sm btn-info btn-detail" 
                data-id="'.$row->id.'" data-month="'.$row->month.'">Detail</button>
                '
            ];
        }

        echo json_encode([
            'data' => $rows
        ]);
    }

    //  public function detail($id)
    // {
    //     echo json_encode(
    //         $this->db->get_where('k_attendance_monthly',['id'=>$id])->row()
    //     );
    // }

    public function detail($id, $month)
    {
        $header = $this->db
                    ->select('a.*, e.full_name, e.employee_code')
                    ->from('k_attendance_monthly a')
                    ->join('k_employees e','e.id = a.employee_id', 'left')
                    ->where('a.id',$id)
                    ->where('a.month',$month)
                    ->get()
                    ->row();

        $startDate = $month;
        $endDate   = substr($month, 0, 7) . date('-t');

        $detail = $this->db
            ->select('a.attendance_date, a.attendance_status, b.shift_name')
            ->from('k_attendances a')
            ->join('k_shifts b', 'b.id = a.shift_id', 'left')
            ->where('a.employee_id', $header->employee_id)
            ->where('a.attendance_date >=', $startDate)
            ->where('a.attendance_date <=', $endDate)
            ->get()
            ->result();
        
        echo json_encode([
            'header'=>$header,
            'detail'=>$detail
        ]);
    }

}