<?php
include "../../src/config.php";

$data = [];

$userdiary_query = "SELECT
id,
duedate, 
note,
state
FROM mis_calendar 
WHERE created_by = :user 
ORDER BY duedate";

$userdiary = datatable::query($userdiary_query, [
    "user" => auth::user_id()
]);

foreach ($userdiary["data"] as $key => $value) {

    if (!isset($data[$value["duedate"]])) {
        $data[$value["duedate"]] = [];
        $data[$value["duedate"]]["userdiary"] = [];
    }

    array_push($data[$value["duedate"]]["userdiary"], $value);
}


// Get Birthdays

$birthday_query = "SELECT 
u.id as user_id,
u.nickname as note, 
u.birthday
FROM users as u 
WHERE birthday IS NOT NULL";


$birthdays = datatable::query($birthday_query);

if ($birthdays["success"] && $birthdays["count"] > 0) {

    foreach ($birthdays["data"] as $key => $value2) {

        $bday = new DateTime($value2["birthday"]);
        $bday2 = new DateTime(date('Y') . "-" . $bday->format('m-d'));

        if (!isset($data[$bday2->format("Y-m-d")])) {
            $data[$bday2->format("Y-m-d")] = [];
        }
        $data[$bday2->format("Y-m-d")]["birthdays"] = [];

        array_push($data[$bday2->format("Y-m-d")]["birthdays"], $value2);
    }
}

ksort($data);

$responsedata = [];

foreach ($data as $date => $value3) {

    $responsedata[] = array_merge($value3, [
        "date" => date('d', strtotime($date)),
        "day" => dayname(date('N', strtotime($date))),
        "month" => date('M', strtotime($date)),
        "year" => date('Y', strtotime($date)),
        "istoday" => (date("Y-m-d") == $date) ? true : false,
    ]);
}

$response["data"] = $responsedata;

//echo json_encode($response);

$calender_dates = [];

$startDate = new DateTime('2025-01-01');
$endDate = new DateTime('2025-12-31');

for ($date = $startDate; $date <= $endDate; $date->modify('+1 day')) {
    $calender_dates[] = [
        "date" => date_format($date, "d"),
        "day" => date_format($date, "D"),
        "month" => date_format($date, "M"),
        "year" => date_format($date, "Y"),
    ];
}

// Initialize the result array
$calender = [];

// Loop through the next 12 months
for ($m = 0; $m < 12; $m++) {

    $startOfMonth = (new DateTime())->modify("first day of +$m month");
    $calender[$m]["year"] = $startOfMonth->format('Y');
    $calender[$m]["monthname"] = $startOfMonth->format('F');

    $dates = [];
    $date = $startOfMonth;

    for ($d = 0; $d < $startOfMonth->format('t'); $d++) {

        $calender[$m]["days"][] = [
            "date" => date_format($date, "d"),
            "day" => date_format($date, "D"),
            "month" => date_format($date, "M"),
            "isweekend" => in_array(date_format($date, "l"), ["Saturday", "Sunday"])
        ];
        $date = $date->modify("+1 days");
    }
}

$response["months"] = $calender;

echo json_encode($response);
