<?php
session_start();
require_once 'includes/database.php';

header('Content-Type: application/json');

if(!isset($_SESSION['username'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$conn = new Database();

try {
    // Delete all existing periods
    $sql = "DELETE FROM timetable_periods";
    $conn->query($sql);
    $conn->execute();

    // Insert default periods
    $sql = "INSERT INTO timetable_periods (period_name, period_number, start_time, end_time, duration, is_break) VALUES
    ('Period 1', 1, '08:00:00', '08:45:00', 45, 0),
    ('Period 2', 2, '08:45:00', '09:30:00', 45, 0),
    ('Short Break', 3, '09:30:00', '09:45:00', 15, 1),
    ('Period 3', 4, '09:45:00', '10:30:00', 45, 0),
    ('Period 4', 5, '10:30:00', '11:15:00', 45, 0),
    ('Long Break', 6, '11:15:00', '11:45:00', 30, 1),
    ('Period 5', 7, '11:45:00', '12:30:00', 45, 0),
    ('Period 6', 8, '12:30:00', '13:15:00', 45, 0),
    ('Period 7', 9, '13:15:00', '14:00:00', 45, 0),
    ('Period 8', 10, '14:00:00', '14:45:00', 45, 0)";

    $conn->query($sql);
    $conn->execute();

    echo json_encode(['success' => true, 'message' => 'Periods reset to default']);
} catch(Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}