<?php
if (strlen(session_id()) < 1) {
session_start();
} 
$_SESSION['sc_json'] = '%relativeSiteAssetPath%/sc_assets/events.json';
$_SESSION['db_name'] = '%relativeSiteAssetPath%/sc_assets/db/calendar.db';
$_SESSION['crudpath'] = "https://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
$crudpath = $_SESSION['crudpath'];

$conn = new PDO('sqlite:%relativeSiteAssetPath%/sc_assets/db/calendar.db');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

//check if the table exists
$query = "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='events2'";
$result = $conn->query($query);
$res = $result->fetch();

if($res[0] > 0){
    //table exists, now check for allDay column
    $query = "PRAGMA table_info(events2);";
    $result = $conn->query($query);
    $res = $result->fetchAll(PDO::FETCH_ASSOC);

    $column_exists = false;
    foreach($res as $column){
        if($column['name'] == 'allDay'){
            $column_exists = true;
            break;
        }
    }

    if(!$column_exists){
        //allDay column does not exist, add it
        $query = "ALTER TABLE events2 ADD COLUMN allDay TEXT;";
        $conn->exec($query);

        // Create a trigger to set 'False' if any NULL value is inserted into the `allDay` column
        $query = "CREATE TRIGGER set_default_allDay
                    AFTER INSERT ON events2
                    WHEN NEW.allDay IS NULL
                    BEGIN
                        UPDATE events2 SET allDay = 'False' WHERE id = NEW.id;
                    END;";
        $conn->exec($query);
    }

} else {
    //table doesn't exist, create it
    $query = "CREATE TABLE IF NOT EXISTS events2 (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, title TEXT, allDay TEXT, ev_start TEXT, ev_end TEXT, event_url TEXT, details TEXT, venue TEXT, venue_add TEXT, social_url TEXT, sponsors TEXT, textColor TEXT, borderColor TEXT, backgroundColor TEXT)";
    $conn->exec($query);

    // Create a trigger to set 'False' if any NULL value is inserted into the `allDay` column
    $query = "CREATE TRIGGER set_default_allDay
                AFTER INSERT ON events2
                WHEN NEW.allDay IS NULL
                BEGIN
                    UPDATE events2 SET allDay = 'False' WHERE id = NEW.id;
                END;";
    $conn->exec($query);
}
?>