<?php
declare(strict_types=1);

/** Minimal SQLite store: bookings table, sequential invoice numbers, no duplicate slot per service. */
final class Store
{
    private PDO $db;
    public function __construct(string $path)
    {
        $this->db = new PDO('sqlite:' . $path, null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
        $this->db->exec('CREATE TABLE IF NOT EXISTS bookings (
            id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, email TEXT, service TEXT,
            date TEXT, time TEXT, qty INTEGER, notes TEXT, invoice TEXT, created TEXT,
            UNIQUE(service, date, time))');
    }
    public function slotTaken(string $service, string $date, string $time): bool
    {
        $q = $this->db->prepare('SELECT 1 FROM bookings WHERE service=? AND date=? AND time=?');
        $q->execute([$service, $date, $time]);
        return (bool)$q->fetchColumn();
    }
    public function nextSeq(): int
    {
        return (int)$this->db->query('SELECT COALESCE(MAX(id),0)+1 FROM bookings')->fetchColumn();
    }
    public function save(array $b, string $invoice): void
    {
        $q = $this->db->prepare('INSERT INTO bookings (name,email,service,date,time,qty,notes,invoice,created)
                                 VALUES (?,?,?,?,?,?,?,?,datetime("now"))');
        $q->execute([$b['name'], $b['email'], $b['service'], $b['date'], $b['time'], (int)$b['qty'], $b['notes'] ?? '', $invoice]);
    }
    public function count(): int { return (int)$this->db->query('SELECT COUNT(*) FROM bookings')->fetchColumn(); }
}
