<?php

declare(strict_types=1);

require_once __DIR__ . '/db.php';

$pdo = getPDO();

$pdo->exec('CREATE TABLE IF NOT EXISTS clients (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    company TEXT,
    email TEXT,
    phone TEXT,
    address TEXT,
    notes TEXT,
    created_at DATETIME
)');

$pdo->exec('CREATE TABLE IF NOT EXISTS templates (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    header_html TEXT,
    footer_html TEXT,
    created_at DATETIME
)');

$pdo->exec('CREATE TABLE IF NOT EXISTS modules (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT NOT NULL,
    content_html TEXT,
    default_required INTEGER DEFAULT 0,
    created_at DATETIME
)');

$pdo->exec('CREATE TABLE IF NOT EXISTS template_modules (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    template_id INTEGER NOT NULL,
    module_id INTEGER NOT NULL,
    sort_order INTEGER DEFAULT 1,
    FOREIGN KEY (template_id) REFERENCES templates(id) ON DELETE CASCADE,
    FOREIGN KEY (module_id) REFERENCES modules(id) ON DELETE CASCADE
)');

$pdo->exec('CREATE TABLE IF NOT EXISTS proposals (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    client_id INTEGER NOT NULL,
    template_id INTEGER NOT NULL,
    modules_json TEXT,
    variables_json TEXT,
    pricing_json TEXT,
    currency TEXT,
    created_at DATETIME,
    FOREIGN KEY (client_id) REFERENCES clients(id),
    FOREIGN KEY (template_id) REFERENCES templates(id)
)');

if (!file_exists(__DIR__ . '/../storage/database.sqlite')) {
    touch(__DIR__ . '/../storage/database.sqlite');
}

echo "Database initialized\n";
