<?php
chdir(dirname(__DIR__));
require_once 'includes/db.php';

echo "=== Payment Attachments Migration ===\n\n";

// 1. Create invoice_payment_attachments table
echo "Creating invoice_payment_attachments table...\n";
try {
    query("CREATE TABLE IF NOT EXISTS invoice_payment_attachments (
        id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        payment_id BIGINT NOT NULL,
        file_name VARCHAR(255) NOT NULL,
        original_name VARCHAR(255) NOT NULL,
        file_size INT DEFAULT 0,
        file_type VARCHAR(100) DEFAULT NULL,
        uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        KEY idx_payment_id (payment_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
    echo "  [OK] Table created (or already exists).\n";
} catch (Exception $e) {
    echo "  [ERROR] " . $e->getMessage() . "\n";
}

// 2. Verify table
echo "\nVerifying table structure...\n";
try {
    $cols = fetchAll("DESCRIBE invoice_payment_attachments");
    foreach ($cols as $col) {
        echo "  " . $col['Field'] . " | " . $col['Type'] . "\n";
    }
} catch (Exception $e) {
    echo "  [ERROR] " . $e->getMessage() . "\n";
}

// 3. Create upload directory
$upload_dir = 'uploads/payment_proofs';
echo "\nChecking upload directory: $upload_dir\n";
if (!is_dir($upload_dir)) {
    if (mkdir($upload_dir, 0755, true)) {
        echo "  [OK] Directory created.\n";
    } else {
        echo "  [ERROR] Failed to create directory.\n";
    }
} else {
    echo "  [OK] Directory already exists.\n";
}

// Create .htaccess to prevent direct script execution but allow file access
$htaccess = $upload_dir . '/.htaccess';
if (!file_exists($htaccess)) {
    file_put_contents($htaccess, "Options -Indexes\n<FilesMatch \"\\.(php|php3|php4|php5|phtml|pl|py|jsp|asp|sh|cgi)$\">\n  Order Allow,Deny\n  Deny from all\n</FilesMatch>\n");
    echo "  [OK] .htaccess security file created.\n";
}

echo "\nMigration complete!\n";
