<?php

require '../config.php';

$res = $conn->query("
SELECT *
FROM leave_requests
WHERE manager_status='Approved'
AND hr_status='Approved'
");

while($leave = $res->fetch_assoc()){

    $employeeId = $leave['employee_id'];

    $start = strtotime(
        $leave['start_date']
    );

    $end = strtotime(
        $leave['end_date']
    );

    for(
        $d = $start;
        $d <= $end;
        $d += 86400
    ){

        $date = date('Y-m-d',$d);

        $check = $conn->query("
            SELECT id
            FROM attendance
            WHERE employee_id=$employeeId
            AND attendance_date='$date'
        ");

        if(!$check->num_rows){

            $stmt = $conn->prepare("
                INSERT INTO attendance
                (
                    employee_id,
                    attendance_date,
                    status,
                    attendance_source,
                    leave_request_id
                )
                VALUES
                (
                    ?,
                    ?,
                    'Leave',
                    'Leave',
                    ?
                )
            ");

            $stmt->bind_param(
                "isi",
                $employeeId,
                $date,
                $leave['id']
            );

            $stmt->execute();
        }
    }
}