<?php
declare(strict_types=1);

ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once 'includes/config.php';
require_once 'session-master.php';

header('Content-Type: application/json; charset=utf-8');

/* =========================
   SESSION CHECK
========================= */
if (!isset($_SESSION['company_id'])) {
    http_response_code(401);
    echo json_encode([]);
    exit;
}

$company_id = (int) $_SESSION['company_id'];

/* =========================
   DB CONNECTION
========================= */
$mysqli = new mysqli(
    DATABASE_HOST,
    DATABASE_USER,
    DATABASE_PASS,
    DATABASE_NAME
);

if ($mysqli->connect_error) {
    http_response_code(500);
    echo json_encode([]);
    exit;
}

/* =========================
   FETCH EVENTS (COMPANY SCOPED)
========================= */
$stmt = $mysqli->prepare("
    SELECT 
        id,
        title,
        start,
        end,
        schedule_type,
        client_location,
        schedule_amount
    FROM event_calendar
    WHERE company_id = ?
");

$stmt->bind_param("i", $company_id);
$stmt->execute();
$result = $stmt->get_result();

$events = [];

while ($row = $result->fetch_assoc()) {
    $events[] = [
        'id'    => (int)$row['id'],
        'title' => $row['title'],
        'start' => $row['start'],
        'end'   => $row['end'] ?: $row['start'],
        'extendedProps' => [
            'type'     => $row['schedule_type'],
            'location' => $row['client_location'],
            'amount'   => number_format((float)$row['schedule_amount'], 2)
        ]
    ];
}

$stmt->close();
$mysqli->close();

echo json_encode($events, JSON_UNESCAPED_UNICODE);
