<?php
// header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");

// session_start();
if (session_status() === PHP_SESSION_NONE) session_start();


// require_once('../db.php');
require_once('../../helper_functions/data_request.php');
include '../../../db.php';
include '../../auth/auth_functions.php';

if (!isset($_SESSION['userid'])) {
    http_response_code(401);
    echo json_encode(["error" => "Unauthorized to access. Please login"]);
    exit;
}

// $response = [];

try {
    // ob_start();
    if (isset($_POST['getScheduleEvents'])) {
        $response = fetchData('schedule_events', []);
        sendJsonResponse(200, $response);
        exit;
    }
    if (isset($_POST['deleteScheduleEvent'])) {

        if (!currentUserHasAccess($pdo, 'property_builder', 'delete')) {
            sendJsonResponse(500, ["error" => "You are not authorized to delete"]);
            exit;
        }
        $scheduleEvent = fetchDataWithId('schedule_events', $_POST['eventId']);
        if (isset($scheduleEvent['title'])) {
            $calendarEvent = fetchData('calendar_added_events', ['title' => $scheduleEvent['title']]);
            if ($calendarEvent[0]['id']) {
                deleteData('calendar_added_events', 'id', $calendarEvent[0]['id']);
                sendJsonResponse(200, 'data has delete now ');
                exit;
            }
        }
        $response = deleteData('schedule_events', 'id', $_POST['eventId']);
        sendJsonResponse(200, $response);
        createAuditLog(
            $_SESSION["userid"],
            'Delete',
            'schedule_events',
            $_POST['eventId'] ?? null,
            $_SESSION["email"] ?? null,
            $_SESSION['property'] ?? null,
            null,
            null,
            'Schedule deleted',
            'high',
            'Schedule'
        ); 
    }

    if (isset($_POST['addScheduleEvent'])) {
        $_POST['property_id'] = $_SESSION['property_id'] ?? $_POST['property_id'] ?? null;
        $keys = ['color', 'isAllDay', 'property_id', 'title', 'eventStartDate', 'eventEndDate', 'day_time_to', 'day_time_from'];
        $data = array_intersect_key($_POST, array_flip($keys));

        $inserted = insertData('schedule_events', $data);
        $response = ['success' => $inserted];

        createAuditLog(
            $_SESSION["userid"],
            'Create',
            'schedule_events',
            $inserted['id'] ?? null,
            $_SESSION["email"] ?? null,
            $_SESSION['property_id'] ?? null,
            null,
            null,
            'Schedule added',
            'high',
            'Schedule'
        );
    }

    if (isset($_POST['add_weekly_schedule'])) {
        if (empty($_POST['command_center_update']) && !currentUserHasAccess($pdo, 'property_builder', 'write')){
            sendJsonResponse(500, ["error" => "You are not authorized to write"]);
            exit;
        }

        if(!empty($_POST['id'])){
            $dataFound=fetchDataSingle("calendar_added_events",["uuid"=>$_POST['id']]);
            if(!empty($dataFound))deleteData('calendar_added_events', "uuid",$_POST['id']);    
        }
        
        $title = $_POST['title'] ?? '';
        $scheduleType = $_POST['schedule_type'] ?? '';
        $priority = $_POST['priority'] ?? '';
        $propertyId = $_SESSION['property_id'] ?? $_POST['property_id'] ?? null;
        $scheduleData = [
            'title' => $title,
            'schedule_type' => $scheduleType,
            'backgroundColor' => $priority,
            'borderColor' => $priority,
            'property_id' => $propertyId,
            'start' => " ",
            'uuid' => generate_uuid_v4()
        ];
        $schedule = insertData('calendar_added_events', $scheduleData);
        if (!empty($schedule['id'])) $scheduleId = $schedule['id'];
        if (!empty($_POST['periods']) && is_array($_POST['periods'])) {
            foreach ($_POST['periods'] as $period) {
                // inserting periods into table
                $periodPayload = [
                    'schedule_id' => $scheduleId,
                    'period_number' => $period['period_number'],
                    'start_time' => $period['start_time'],
                    'end_time' => $period['end_time'],
                    'start_date' => $period['start_date'],
                    'end_date' => $period['end_date']
                ];
                $insertedPeriod = insertData('schedule_periods', $periodPayload);
                if (!empty($insertedPeriod['id'])) $periodId = $insertedPeriod['id'];

                foreach ($period['days'] as $dayData) {
                    $daysPayload = [
                        'period_id' => $periodId,
                        'day' => $dayData['day'],
                        'startTime' => $dayData['start_time'],
                        'endTime' => $dayData['end_time'],
                        'is_active' => $dayData['is_active'] == "true" ? 1 : 0
                    ];
                    insertData('schedule_period_days', $daysPayload);
                }
            }
        }

        createAuditLog(
            $_SESSION["userid"],
            'Create',
            'schedule_events',
            $inserted['id'] ?? null,
            $_SESSION["email"] ?? null,
            $propertyId ?? null,
            null,
            null,
            'Schedule added with the title '.$title,
            'high',
            'Schedule'
        );
        sendJsonResponse(200, [
            "success" => true,
            "data" => "Schedule has been added",
        ]);
        exit;
    }

    if (isset($_POST['edit_weekly_schedule'])) {
        $propertyId = $_SESSION['property_id'] ?? $_POST['property_id'] ?? null;
        $editSchedule = fetchDataSingle("calendar_added_events", ["id" => $_POST['id']]);
        if (empty($editSchedule)) {
            sendJsonResponse(500, ["error" => "Could not find any data using the id" . $_POST['id']]);
        }
        $allPeriods = fetchData("schedule_periods", ["schedule_id" => $editSchedule["id"]]);

        foreach ($allPeriods as $period) {
            deleteData("schedule_period_days", "period_id", $period["id"]);
        }
        deleteData("schedule_periods", "schedule_id", $_POST['id']);

        $where = 'id = :id';
        $params = ['id' => $_POST['id']];
        $dataToUpdate = [
            'title' => $_POST['title'],
            'schedule_type' => $_POST['schedule_type'],
            'backgroundColor' => $_POST['priority'],
            'borderColor' => $_POST['priority'],
            'property_id' => $_POST['property_id'],
        ];
        updateTable('calendar_added_events', $dataToUpdate, $where, $params);

        if (!empty($_POST['periods']) && is_array($_POST['periods'])) {
            foreach ($_POST['periods'] as $period) {
                $periodPayload = [
                    'schedule_id' => $_POST["id"],
                    'period_number' => $period['period_number'],
                    'start_time' => $period['start_time'],
                    'end_time' => $period['end_time'],
                    'start_date' => $period['start_date'],
                    'end_date' => $period['end_date']
                ];
                $insertedPeriod = insertData('schedule_periods', $periodPayload);
                if (!empty($insertedPeriod['id'])) $periodId = $insertedPeriod['id'];
                // Insert Period Days
                foreach ($period['days'] as $dayData) {
                    $daysPayload = [
                        'period_id' => $periodId,
                        'day' => $dayData['day'],
                        'startTime' => $dayData['start_time'],
                        'endTime' => $dayData['end_time'],
                        'is_active' => $dayData['is_active'] == "true" ? 1 : 0
                    ];
                    insertData('schedule_period_days', $daysPayload);
                }
            }
        }

        createAuditLog(
            $_SESSION["userid"],
            'Update',
            'calendar_added_events',
            $inserted['id'] ?? null,
            $_SESSION["email"] ?? null,
            $propertyId ?? null,
            null,
            null,
            'Schedule updated',
            'high',
            'Schedule'
        );

        $scheduleData = fetchDataSingle("hardwares_settings",["timer"=>$_POST['id'],"property_id"=>$propertyId]);
        $isControlingDevices=false;
        if(!empty($scheduleData))$isControlingDevices=true;
        sendJsonResponse(200, [
            "success" => true,
            "data" => "Updated successfully",
            "isControlingDevices" => $isControlingDevices,
            "updated_id" => $_POST['id']
        ]);
        exit;
    }
    if (isset($_POST['get_weekly_schedule'])) {
        if (empty($_POST['property_id'])) $_POST['property_id'] = $_SESSION['property'];
        $propertyId = $_POST['property_id'];
        if (!$propertyId) {
            sendJsonResponse(400, ["error" => "Property ID is required."]);
            exit;
        }

        $query = "
            SELECT 
                s.id AS schedule_id,
                s.title AS schedule_title,
                s.schedule_type,
                s.backgroundColor,
                s.property_id,
                p.id AS period_id,
                p.period_number,
                p.start_time,
                p.end_time,
                p.start_date,
                p.end_date,
                pd.id AS day_id,
                pd.day,
                pd.startTime,
                pd.endTime,
                pd.is_active
            FROM 
                calendar_added_events s
            INNER JOIN 
                schedule_periods p ON s.id = p.schedule_id
            INNER JOIN 
                schedule_period_days pd ON p.id = pd.period_id
            WHERE 
                s.property_id = :property_id
            ORDER BY 
                s.id, p.period_number, FIELD(pd.day, 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat')
        ";

        $result = fetchDataWithJoins($query, [':property_id' => $propertyId]);

        if (empty($result)) {
            $custom_schedules = fetchData("calendar_added_events", ["property_id" => $propertyId,"is_weekly"=>1]);
            sendJsonResponse(200, array_values($custom_schedules));
            exit;
        }

        // Organize Data into JSON Format
        $schedules = [];
        foreach ($result as $row) {
            $scheduleId = $row['schedule_id'];
            $periodId = $row['period_id'];

            if (empty($schedules[$scheduleId])) {
                $schedules[$scheduleId] = [
                    'schedule_id' => $scheduleId,
                    'backgroundColor' => $row["backgroundColor"],
                    'schedule_type' => $row["schedule_type"],
                    'title' => $row['schedule_title'],
                    'property_id' => $row['property_id'],
                    'periods' => []
                ];
            }

            if (empty($schedules[$scheduleId]['periods'][$periodId])) {
                $schedules[$scheduleId]['periods'][$periodId] = [
                    'period_id' => $periodId,
                    'period_number' => $row['period_number'],
                    'start_time' => $row['start_time'],
                    'end_time' => $row['end_time'],
                    'start_date' => $row['start_date'],
                    'end_date' => $row['end_date'],
                    'days' => []
                ];
            }

            // Add active day status with day_id
            $schedules[$scheduleId]['periods'][$periodId]['days'][$row['day']] = [
                'day_id' => $row['day_id'],
                'day_startTime' => $row['startTime'],
                'day_endTime' => $row['endTime'],
                'is_active' => (bool) $row['is_active']
            ];
        }

        // Re-index the periods for clean JSON output
        foreach ($schedules as &$schedule) {
            $schedule['periods'] = array_values($schedule['periods']);
        }

        $custom_schedules = fetchData("calendar_added_events", ["property_id" => $propertyId,"is_weekly"=>1]);
        $mergedSchedules = array_merge($schedules, $custom_schedules);
        sendJsonResponse(200, array_values($mergedSchedules));
        exit;
    }

    if (isset($_POST['get_weekly_schedule_by_id'])) {
        if (empty($_POST['property_id'])) $_POST['property_id'] = $_SESSION['property'];
        $propertyId = $_POST['property_id'];
        $scheduleId = $_POST['schedule_id'] ?? null;
        if (!$propertyId) {
            sendJsonResponse(400, ["error" => "Property ID is required."]);
            exit;
        }
        if (!$scheduleId) {
            sendJsonResponse(400, ["error" => "Schedule ID is required."]);
            exit;
        }

        $query = "
            SELECT 
                s.id AS schedule_id,
                s.title AS schedule_title,
                s.schedule_type,
                s.backgroundColor,
                s.property_id,
                p.id AS period_id,
                p.period_number,
                p.start_time,
                p.end_time,
                p.start_date,
                p.end_date,
                pd.id AS day_id,
                pd.day,
                pd.startTime,
                pd.endTime,
                pd.is_active
            FROM 
                calendar_added_events s
            INNER JOIN 
                schedule_periods p ON s.id = p.schedule_id
            INNER JOIN 
                schedule_period_days pd ON p.id = pd.period_id
            WHERE 
                s.property_id = :property_id AND s.id = :schedule_id
            ORDER BY 
                s.id, p.period_number, FIELD(pd.day, 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat')
        ";

        $result = fetchDataWithJoins($query, [':property_id' => $propertyId, ':schedule_id' => $scheduleId]);

        if (empty($result)) {
            // Fallback to a simple fetch if no joined rows (e.g., schedule exists without periods/days)
            $custom_schedule = fetchDataSingle("calendar_added_events", ["property_id" => $propertyId, "id" => $scheduleId, "is_weekly" => 1]);
            if (!$custom_schedule) {
                sendJsonResponse(404, ["error" => "Weekly schedule not found."]);
                exit;
            }
            sendJsonResponse(200, $custom_schedule);
            exit;
        }

        // Organize Data into JSON Format for a single schedule
        $schedule = [];
        foreach ($result as $row) {
            $periodId = $row['period_id'];
            if (empty($schedule)) {
                $schedule = [
                    'schedule_id' => $row['schedule_id'],
                    'backgroundColor' => $row['backgroundColor'],
                    'schedule_type' => $row['schedule_type'],
                    'title' => $row['schedule_title'],
                    'property_id' => $row['property_id'],
                    'periods' => []
                ];
            }

            if (empty($schedule['periods'][$periodId])) {
                $schedule['periods'][$periodId] = [
                    'period_id' => $periodId,
                    'period_number' => $row['period_number'],
                    'start_time' => $row['start_time'],
                    'end_time' => $row['end_time'],
                    'start_date' => $row['start_date'],
                    'end_date' => $row['end_date'],
                    'days' => []
                ];
            }

            $schedule['periods'][$periodId]['days'][$row['day']] = [
                'day_id' => $row['day_id'],
                'day_startTime' => $row['startTime'],
                'day_endTime' => $row['endTime'],
                'is_active' => (bool) $row['is_active']
            ];
        }

        // Re-index the periods for clean JSON output
        $schedule['periods'] = array_values($schedule['periods']);

        sendJsonResponse(200, [
            "success" => true,
            "data" => $schedule
        ]);
        exit;
    }

    if (isset($_POST['delete_weekly_schedule'])) {

        $where = 'id = :id';
        $params = ['id' => $_POST['id']];
        $dataToUpdate = [
            'is_active' => 0,
        ];
        updateTable('schedule_period_days', $dataToUpdate, $where, $params);

        if (!empty($_POST["schedule_id"])) {
            $periods = fetchData("schedule_periods", ["schedule_id" => $_POST["schedule_id"]]);
            if (!empty($periods) && is_array($periods)) {
                foreach ($periods as $period) {
                    $periodDays = fetchData("schedule_period_days", ["period_id" => $period['id']]);
                    $hasActiveDay = false;
                    foreach ($periodDays as $dayData) {
                        if ($dayData['is_active'] == 1) {
                            $hasActiveDay = true;
                            break;
                        }
                    }
                    if (!$hasActiveDay) {
                        deleteData("schedule_periods", "id", $period['id']);
                    }
                }
            }
            $periods = fetchData("schedule_periods", ["schedule_id" => $_POST["schedule_id"]]);
            if (empty($periods)) {
                deleteData("calendar_added_events", "id", $_POST["schedule_id"]);
            }
            $schedule_automations = fetchData("hardware_automations",["device_id"=>$_POST["schedule_id"]]);
            
        }
        sendJsonResponse(200, [
            "success" => true,
            "data" => "Deleted successfully"
        ]);
        exit;
    }

    if (isset($_POST['complete_delete_weekly_schedule'])) {
        if(!currentUserHasAccess($pdo, 'property_builder', 'delete')){
            sendJsonResponse(500, ["error" => "You are not authorized to delete"]);
            exit;
        }
        $schedule = fetchDataSingle("calendar_added_events",["id"=>$_POST['schedule_id']]);
        if(empty($schedule)){
            sendJsonResponse(400, ["error" => "Data not found against the id: ".$_POST['schedule_id']]);
            exit;
        }
        $where = 'id = :id';
        $params = ['id' => $_POST['schedule_id']];        
        deleteData('calendar_added_events', 'id', $_POST['schedule_id']);        
        sendJsonResponse(200, [
            "success" => true,
            "data" => "Deleted successfully"
        ]);
        exit;
    }

    if (isset($_POST['update_on_drag_drop_weekly_schedule'])) {
        $periodDay = fetchDataSingle("schedule_period_days", ["id" => $_POST['dayId']]);
        if ($periodDay["day"] == $_POST['day']) {
            $periodDayPayload = [
                "period_id" => $_POST['period_id'],
                "day" => $_POST['day'],
                "startTime" => $_POST['startTime'],
                "endTime" => $_POST['endTime']
            ];
            $where = 'id = :id';
            $params = ['id' => $_POST['dayId']];
            $updated = updateTable('schedule_period_days', $periodDayPayload, $where, $params);
            sendJsonResponse(200, [
                "success" => true,
                "data" => "Updated successfully",
                "updated" => $updated
            ]);
            exit;
        } else {
            $dayPayload = [
                "is_active" => 0,
                "startTime" => null,
                "endTime" => null
            ];
            $whereDay1 = 'id = :id';
            $paramsDay1 = ['id' => $_POST['dayId']];
            updateTable('schedule_period_days', $dayPayload, $whereDay1, $paramsDay1);

            $periodDayToUpdate = fetchDataSingle("schedule_period_days", ["period_id" => $_POST['period_id'], "day" => $_POST['day']]);
            $periodDayToUpdate["is_active"] = 1;
            $periodDayToUpdate["startTime"] = $_POST['startTime'];
            $periodDayToUpdate["endTime"] = $_POST['endTime'];

            $whereDay2 = 'id = :id';
            $paramsDay2 = ['id' => $periodDayToUpdate['id']];
            updateTable('schedule_period_days', $periodDayToUpdate, $whereDay2, $paramsDay2);
            sendJsonResponse(200, [
                "success" => true,
                "data" => "Updated successfully",
                "day" => $periodDayToUpdate
            ]);
            exit;
        }
    }

    if (isset($_POST['addEventToCalendar'])) {

        if (isset($_POST['title'])) {
            $alreadyExists = fetchData('calendar_added_events', ['title' => $_POST['title']]);
            if (isset($alreadyExists[0]['id'])) {
                sendJsonResponse(500, ["error" => "Event already found. Please add new event"]);
                exit;
            }
        }
        $_POST['property_id'] = $_SESSION['property_id'] ?? $_POST['property_id'] ?? null;
        $keys = ['title', 'start', 'end', 'backgroundColor', 'schedule_type', 'borderColor', 'allDay', 'property_id', 'day_time_from', 'day_time_to'];
        $data = array_intersect_key($_POST, array_flip($keys));

        $inserted = insertData('calendar_added_events', $data);
        createAuditLog(
            $_SESSION["userid"],
            'Create',
            'calendar_added_events',
            $inserted['id'] ?? null,
            $_SESSION["email"],
            $_POST['property_id'] ?? null,
            null,
            null,
            'Schedule calendar added',
            'high',
            'Schedule'
        );
        sendJsonResponse(200, ['message' => "Data has added ", 'data' => $inserted]);
        exit;
    }

    if (isset($_POST['getAddedEventsToCalendar'])) {
        $data = fetchData('calendar_added_events', ['is_default' => NULL]);
        $response = $data;
    }

    if (isset($_POST['updateEventToCalendar'])) {
        $data = [
            'title' => $_POST['data']['title'],
            'start' => $_POST['data']['start'],
            'allDay' => $_POST['data']['allDay'],
            'end' => $_POST['data']['end'],
        ];
        $where = 'id = :id';
        $params = ['id' => $_POST['data']['id']];
        $updateSuccess = updateTable('calendar_added_events', $data, $where, $params);
        $response = $updateSuccess;
        createAuditLog(
            $_SESSION["userid"],
            'Update',
            'calendar_added_events',
            $_POST['data']['id'] ?? null,
            $_SESSION["email"],
            $_SESSION['property_id'] ?? null,
            null,
            null,
            'Schedule calendar updated',
            'high',
            'Schedule'
        );
        // $response =$_POST['data'];

    }

    if (isset($_POST['deleteEventFromCalendar'])) {

        if (!currentUserHasAccess($pdo, 'property_builder', 'delete')) {
            sendJsonResponse(500, ["error" => "You are not authorized to delete"]);
            exit;
        }
        $data = deleteData('calendar_added_events', 'id', $_POST['id']);
        $response = $data;
        createAuditLog(
            $_SESSION["userid"],
            'Create',
            'calendar_added_events',
            $inserted['id'] ?? null,
            $_SESSION["email"],
            $_SESSION['property_id'] ?? null,
            null,
            null,
            'Schedule calendar added',
            'high',
            'Schedule'
        );
        sendJsonResponse(200, ['Deleted successfully']);
    }

    if (isset($_POST['updateCalendarAddedEventThroughModal'])) {
        $keys = ['title', 'allDay', 'day_time_from', 'schedule_type', 'day_time_to', 'start', 'end', 'borderColor', 'backgroundColor'];
        $data = array_intersect_key($_POST, array_flip($keys));

        $where = 'id = :id';
        $params = ['id' => $_POST['id']];
        $updateSuccess = updateTable('calendar_added_events', $data, $where, $params);
        $response = $updateSuccess;
        createAuditLog(
            $_SESSION["userid"],
            'Update',
            'calendar_added_events',
            $_POST['id'] ?? null,
            $_SESSION["email"],
            $_SESSION['property_id'] ?? null,
            null,
            null,
            'Schedule calendar updated',
            'high',
            'Schedule'
        );
    }

    if (isset($_POST['edit_custom_calendar_schedule_request'])) {
        if (!currentUserHasAccess($pdo, 'property_builder', 'write')) {
            sendJsonResponse(500, ["error" => "You are not authorized to write"]);
            exit;
        }
        $fetched=fetchDataSingle("calendar_added_events",['uuid'=>$_POST['id']]); 
        if(empty($fetched)){
            sendJsonResponse(400, ["error" => "Data not found against the id: ".$_POST['id']]);
            exit;
        }

        $keys = ['title', 'uuid', "is_weekly", 'schedule_type', 'backgroundColor', 'borderColor', 'start', 'end', 'property_id'];
        $data = array_intersect_key($_POST, array_flip($keys));

        $where = 'uuid = :id';
        $params = ['id' => $_POST['id']];
        $updateSuccess = updateTable('calendar_added_events', $data, $where, $params);

        createAuditLog(
            $_SESSION["userid"],
            'Update',
            'calendar_added_events',
            $_POST['id'] ?? null,
            $_SESSION["email"],
            $_SESSION['property_id'] ?? null,
            null,
            null,
            'Schedule calendar update',
            'high',
            'Schedule'
        );

        sendJsonResponse(200, [
            "success" => true,
            "data" => "updated successfully",
        ]);
        exit;
    }

    if (isset($_POST['add_custom_calendar_schedule_request'])) {
        if (!currentUserHasAccess($pdo, 'property_builder', 'write')) {
            sendJsonResponse(500, ["error" => "You are not authorized to write"]);
            exit;
        }

        if (empty($_POST['property_id'])) $_POST['property_id'] = $_SESSION['property'];
        if (!$_POST['property_id']) {
            sendJsonResponse(400, ["error" => "Property ID is required."]);
            exit;
        }
        if(!empty($_POST['id'])){
            $dataFound=fetchDataSingle("calendar_added_events",['id'=>$_POST['id']]);
            if(!empty($dataFound)){
                deleteData("calendar_added_events","id",$_POST['id']);
            }
        }
        $_POST['uuid'] = generate_uuid_v4();
        $_POST['is_weekly'] = 1;
        $keys = ['title', 'uuid', "is_weekly", 'schedule_type', 'backgroundColor', 'borderColor', 'start', 'end', 'property_id'];
        $data = array_intersect_key($_POST, array_flip($keys));
        $response = insertData('calendar_added_events', $data);
        createAuditLog(
            $_SESSION["userid"],
            'Create',
            'calendar_added_events',
            $_POST['id'] ?? null,
            $_SESSION["email"],
            $_SESSION['property_id'] ?? null,
            null,
            null,
            'Schedule calendar added',
            'high',
            'Schedule'
        );

        sendJsonResponse(200, [
            "success" => true,
            "data" => "Added successfully",
        ]);
        exit;
    }

    if (isset($_POST['delete_custom_calendar_schedule'])) {
        if (!currentUserHasAccess($pdo, 'property_builder', 'delete')) {
            sendJsonResponse(500, ["error" => "You are not authorized to delete"]);
            exit;
        }

        if (empty($_POST['schedule_uuid'])) {
            sendJsonResponse(400, ["error" => "Id is required."]);
            exit;
        }
        $response = deleteData('calendar_added_events', 'uuid', $_POST['schedule_uuid']);








        createAuditLog(
            $_SESSION["userid"],
            'Delete',
            'calendar_added_events',
            $_POST['id'] ?? null,
            $_SESSION["email"],
            $_SESSION['property_id'] ?? null,
            null,
            null,
            'Schedule calendar deleted',
            'high',
            'Schedule'
        );
        if(!$response)sendJsonResponse(500, ["error" => "Could not delete."]);
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response,
        ]);
        exit;
    }

    if (isset($_POST['edit_drag_drop_custom_calendar_schedule_request'])) {
        if (!currentUserHasAccess($pdo, 'property_builder', 'write')) {
            sendJsonResponse(401, ["error" => "You are not authorized to write"]);
            exit;
        }
        if (empty($_POST['uuid'])) {
            sendJsonResponse(400, ["error" => "Id is required."]);
            exit;
        }

        $fetched=fetchDataSingle("calendar_added_events",["uuid"=>$_POST['uuid']]);
        if(empty($fetched)){
            sendJsonResponse(400, ["error" => "Data not found against the provided id"]);
            exit;
        }

        $keys = ['title', 'uuid', "is_weekly", 'schedule_type', 'backgroundColor', 'borderColor', 'start', 'end', 'property_id'];
        $data = array_intersect_key($_POST, array_flip($keys));
        $where = 'uuid = :id';
        $params = ['id' => $_POST['uuid']];
        $updateSuccess = updateTable('calendar_added_events', $data, $where, $params);
        createAuditLog(
            $_SESSION["userid"],
            'Update',
            'calendar_added_events',
            $_POST['id'] ?? null,
            $_SESSION["email"],
            $_SESSION['property_id'] ?? null,
            null,
            null,
            'Schedule calendar updated on drag',
            'high',
            'Schedule'
        );
        sendJsonResponse(200, [
            "success" => $fetched,
            "data" => "updating now successfully",
            "updateSuccess" => $updateSuccess,
        ]);
        exit;
    }
} catch (\Throwable $th) {
    sendJsonResponse(500, ["error" => "Server error: " . $th->getMessage()]);
    exit;
}

function generate_uuid_v4()
{
    $data = random_bytes(16);
    $data[6] = chr((ord($data[6]) & 0x0f) | 0x40);
    $data[8] = chr((ord($data[8]) & 0x3f) | 0x80);

    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}

echo json_encode($response);
