<?php
declare(strict_types=1);

require_once __DIR__ . '/db.php';

$pdo = db();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

$jsonFile = __DIR__ . '/uae_civil_procedure_42_2022_articles.json';
if (!is_file($jsonFile)) {
    exit("JSON file not found: {$jsonFile}\n");
}

$data = json_decode((string)file_get_contents($jsonFile), true);
if (!is_array($data)) {
    exit("Invalid JSON data\n");
}

$pdo->exec("
CREATE TABLE IF NOT EXISTS laws_articles (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    source_type VARCHAR(20) NOT NULL,
    source_title VARCHAR(255) NOT NULL,
    law_name VARCHAR(255) NOT NULL,
    law_number INT NOT NULL,
    law_year INT NOT NULL,
    article_number INT NOT NULL,
    article_title VARCHAR(255) NOT NULL,
    article_text LONGTEXT NOT NULL,
    created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY idx_law_article (law_number, law_year, article_number),
    KEY idx_source_type (source_type)
) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
");

$stmt = $pdo->prepare("
INSERT INTO laws_articles
(source_type, source_title, law_name, law_number, law_year, article_number, article_title, article_text)
VALUES
(:source_type, :source_title, :law_name, :law_number, :law_year, :article_number, :article_title, :article_text)
");

$pdo->beginTransaction();

try {
    foreach ($data as $row) {
        $stmt->execute([
            ':source_type'    => (string)($row['source_type'] ?? ''),
            ':source_title'   => (string)($row['source_title'] ?? ''),
            ':law_name'       => (string)($row['law_name'] ?? ''),
            ':law_number'     => (int)($row['law_number'] ?? 0),
            ':law_year'       => (int)($row['law_year'] ?? 0),
            ':article_number' => (int)($row['article_number'] ?? 0),
            ':article_title'  => (string)($row['article_title'] ?? ''),
            ':article_text'   => (string)($row['article_text'] ?? ''),
        ]);
    }

    $pdo->commit();
    echo "Done: imported " . count($data) . " rows into laws_articles\n";
} catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    echo "Import failed: " . $e->getMessage() . "\n";
}
