<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/admin/system/settings/db.php';
session_start();

$user_id = $_SESSION['memberId'];
$providerCheckSite = $DB->prepare("SELECT * FROM provider WHERE id = ?");
$providerCheckSite->execute(array($user_id));
$providerChk = $providerCheckSite->fetch(PDO::FETCH_ASSOC);

if (!$providerChk) {
    echo json_encode(['newAppointment' => false]);
    exit;
}

$lastSeenAppointmentId = $providerChk['lastSeenAppointmentId'];

if ($providerChk['isAdmin'] == '1') {
    $query = $DB->query("SELECT id FROM appointments ORDER BY id DESC LIMIT 1");
} else {
    $query = $DB->prepare("SELECT id FROM appointments WHERE providerID = :user_id ORDER BY id DESC LIMIT 1");
    $query->execute(['user_id' => $user_id]);
}

$latestAppointment = $query->fetch(PDO::FETCH_ASSOC);

if ($latestAppointment && $latestAppointment['id'] > $lastSeenAppointmentId) {
    $update = $DB->prepare("UPDATE provider SET lastSeenAppointmentId = :last_id WHERE id = :user_id");
    $update->execute([
        'last_id' => $latestAppointment['id'],
        'user_id' => $user_id
    ]);

    echo json_encode([
        'newAppointment' => true,
        'lastAppointmentId' => $latestAppointment['id']
    ]);
} else {
    echo json_encode(['newAppointment' => false]);
}
?>