<?php
    require_once '../../autoload.php';

    require_once '../../html/caldav_task.php';

    $result = array (
            "status"    => 'KO',
            "id"    => -1
    );

    define ( 'RECURRENCE_UNIQUE',   0 );
    define ( 'RECURRENCE_DAILY',    1 );
    define ( 'RECURRENCE_WEEKLY',   2 );
    define ( 'RECURRENCE_MONTHLY',  3 );
    define ( 'RECURRENCE_QUATERLY', 4 );
    define ( 'RECURRENCE_YEARLY',   5 );


    function adjustToDayOfWeek ( DateTimeImmutable $date, int $desiredDayOfWeek): DateTimeImmutable 
    {
        $currentDay = (int)$date->format('w');
        $diff = ($desiredDayOfWeek - $currentDay + 7) % 7;
        return $date->modify("+{$diff} days");
    }

    function CreateTasks ( PDO $pdo, int $taskId, string $title, $description, DateTimeImmutable $dueDate, $staff_member_ids ): void 
    {
        error_log ( "=== CreateTasks ===");
        error_log ( " taskId : " .$taskId );
        error_log ( " title : " .$title );
        error_log ( " dueDate : " .$dueDate->format('Y-m-d') );

        $check = $pdo->prepare ( "SELECT 1 FROM task WHERE task_master_id = ? AND due_date = ?" );
        $check->execute([$taskId, $dueDate->format('Y-m-d')]);
    
        if ( !$check->fetchColumn () ) 
        {
            $s = $pdo->prepare ( "INSERT INTO task (title, description, due_date, task_master_id ) VALUES (:title, :description, :due_date, :task_master_id ) RETURNING id;");
            $dueDateFmt = $dueDate->format('Y-m-d');
            $s->bindParam ( ':title',          $title                       );
            $s->bindParam ( ':description',    $description                 );
            $s->bindParam ( ':due_date',       $dueDateFmt                  );
            $s->bindParam ( ':task_master_id', $taskId                      );

            if ( $s->execute () == true )
            {
                $task_id    = $s->fetchColumn ();
                $status_id  = 3;    // Planned
                $sm_array   = explode ( ',', $staff_member_ids );

                foreach ( $sm_array as $staff_member_id )
                {
                    $s1 = $pdo->prepare ( "INSERT INTO task_link (task_id, staff_member_id, status_id, status_date) VALUES (:task_id, :staff_member_id, :status_id, NOW())" );
                    $s1->bindParam ( ':task_id',         $task_id            );
                    $s1->bindParam ( ':staff_member_id', $staff_member_id    );
                    $s1->bindParam ( ':status_id',       $status_id          );

                    $s1->execute ();

                    // Send VTODO to calendars
                    SendVTODO ( $staff_member_id, $title, $description, $dueDateFmt );
                }
            }
        }        
    }

    $pdo = getPDO ();

    $today = new DateTimeImmutable();
    $limitDate = $today->modify('+120 days');

    // $stmt = $pdo->query ( "SELECT * FROM task_master WHERE active = TRUE" );
    $stmt = $pdo->query ( "with t as (select tm.id,tml.staff_member_id, tm.title, tm.description, tm.day_of_week,tm.start_date, tm.end_date, tm.recurrence from task_master tm left join task_master_link tml on tm.id = tml.task_master_id ) select t.id, t.title, t.description, t.day_of_week, t.start_date, t.end_date, t.recurrence, array_to_string(array_agg(staff_member_id ), ',') as staff_member_ids from t group by id, title, description, day_of_week, start_date, end_date, recurrence" );

    while ( $task = $stmt->fetch(PDO::FETCH_ASSOC) ) 
    {
        $startDate          = new DateTimeImmutable($task['start_date']);
        $endDate            = $task['end_date'] ? new DateTimeImmutable($task['end_date']) : $limitDate;
        $endDate            = min($endDate, $limitDate);
        $staffMemberIDs     = $task['staff_member_ids'];
        

        error_log ( "*** TITLE : " . $task['title'] . " / " . $task['recurrence'] );
        error_log ( " Val : " . $staffMemberIDs ); 
    
        switch ( (int)$task['recurrence'] ) 
        {
            case RECURRENCE_UNIQUE:
                if ($startDate >= $today && $startDate <= $limitDate) 
                {
                    CreateTasks($pdo, $task['id'], $task['title'], $task['description'], $startDate, $staffMemberIDs );
                }
                break;

            case RECURRENCE_DAILY:
                for ($date = $startDate; $date <= $endDate; $date = $date->modify('+1 day')) 
                {
                    if ($date >= $today) 
                    {
                        CreateTasks($pdo, $task['id'], $task['title'], $task['description'], $date, $staffMemberIDs );
                    }
                }
                break;

            case RECURRENCE_WEEKLY:
                for ($date = $startDate; $date <= $endDate; $date = $date->modify('+1 week')) 
                {
                    if ($task['day_of_week'] >= 0) 
                    {
                        $date = adjustToDayOfWeek($date, (int)$task['day_of_week']);
                    }
                    if ($date >= $today && $date <= $limitDate) 
                    {
                        CreateTasks($pdo, $task['id'], $task['title'], $task['description'], $date, $staffMemberIDs );
                    }
                }
                break;

            case RECURRENCE_MONTHLY:
                for ($date = $startDate; $date <= $endDate; $date = $date->modify('+1 month')) 
                {
                    if ($task['day_of_week'] >= 0) 
                    {
                        $date = adjustToDayOfWeek($date, (int)$task['day_of_week']);
                    }
                    if ($date >= $today && $date <= $limitDate) 
                    {
                        CreateTasks($pdo, $task['id'], $task['title'], $task['description'], $date, $staffMemberIDs );
                    }
                }
                break;

            case RECURRENCE_QUATERLY:
                for ($date = $startDate; $date <= $endDate; $date = $date->modify('+3 months')) 
                {
                    if ($task['day_of_week'] >= 0) 
                    {
                        $date = adjustToDayOfWeek($date, (int)$task['day_of_week']);
                    }
                    if ($date >= $today && $date <= $limitDate) 
                    {
                        CreateTasks($pdo, $task['id'], $task['title'], $task['description'], $date, $staffMemberIDs );
                    }
                }
                break;

            case RECURRENCE_YEARLY:
                for ($date = $startDate; $date <= $endDate; $date = $date->modify('+1 year')) 
                {
                    if ($task['day_of_week'] >= 0) 
                    {
                        $date = adjustToDayOfWeek($date, (int)$task['day_of_week']);
                    }
                    if ($date >= $today && $date <= $limitDate) 
                    {
                        CreateTasks($pdo, $task['id'], $task['title'], $task['description'], $date, $staffMemberIDs );
                    }
                }
                break;
        }
    }
?>