<?php
require_once __DIR__ . '/app/bootstrap/init.php';
use App\Core\Database;

try {
    $db = Database::getInstance();
    
    echo "Running Phase 2 Migrations...\n";
    
    // 1. user_devices
    $db->exec("
        CREATE TABLE IF NOT EXISTS user_devices (
            id CHAR(36) PRIMARY KEY,
            user_id CHAR(36) NOT NULL,
            device_fingerprint VARCHAR(64) NOT NULL,
            device_name VARCHAR(100),
            platform ENUM('android','ios') NOT NULL,
            app_version VARCHAR(20),
            push_token TEXT NULL,
            device_secret VARCHAR(255) NULL,
            is_trusted BOOLEAN DEFAULT FALSE,
            last_seen_at DATETIME,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
            UNIQUE KEY uq_user_device (user_id, device_fingerprint)
        )
    ");
    echo "Created user_devices table.\n";

    // 2. invoice_batches
    $db->exec("
        CREATE TABLE IF NOT EXISTS invoice_batches (
            id CHAR(36) PRIMARY KEY,
            tenant_id CHAR(36) NOT NULL,
            company_id CHAR(36) NOT NULL,
            uploaded_by CHAR(36) NOT NULL,
            total_images INT NOT NULL DEFAULT 0,
            processed_images INT NOT NULL DEFAULT 0,
            status ENUM('uploading','processing','done','partial_fail') DEFAULT 'uploading',
            source ENUM('mobile_scan','web_upload','whatsapp') DEFAULT 'mobile_scan',
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            completed_at DATETIME NULL,
            FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
            FOREIGN KEY (company_id) REFERENCES companies(id) ON DELETE CASCADE,
            FOREIGN KEY (uploaded_by) REFERENCES users(id) ON DELETE SET NULL
        )
    ");
    echo "Created invoice_batches table.\n";

    // 3. invoice_processing_queue
    $db->exec("
        CREATE TABLE IF NOT EXISTS invoice_processing_queue (
            id INT AUTO_INCREMENT PRIMARY KEY,
            batch_id CHAR(36) NOT NULL,
            invoice_id CHAR(36) NULL,
            tenant_id CHAR(36) NOT NULL,
            image_path VARCHAR(500) NOT NULL,
            status ENUM('pending','processing','done','failed') DEFAULT 'pending',
            attempts INT DEFAULT 0,
            error_message TEXT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            processed_at DATETIME NULL,
            FOREIGN KEY (batch_id) REFERENCES invoice_batches(id) ON DELETE CASCADE
        )
    ");
    $db->exec("CREATE INDEX IF NOT EXISTS idx_status_tenant ON invoice_processing_queue (status, tenant_id)");
    echo "Created invoice_processing_queue table.\n";

    echo "Phase 2 Migrations completed successfully.\n";

} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
