<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once 'bd/myData.php';
require_once 'auth.php';
include 'cors.php';
setupCORS();


if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('HTTP/1.1 200 OK');
    exit();
}




function checkAndCreateProfileTable($pdo) {
    try {

        $stmt = $pdo->query("SHOW TABLES LIKE 'profile'");
        if ($stmt->rowCount() == 0) {

            $sql = "CREATE TABLE IF NOT EXISTS `profile` (
                `id_profile` int(11) NOT NULL AUTO_INCREMENT,
                `nom_profile` varchar(50) NOT NULL,
                `permissions` text DEFAULT NULL,
                `date_cre` timestamp NULL DEFAULT current_timestamp(),
                `date_upd` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
                `user_cre` varchar(50) DEFAULT NULL,
                `user_upd` varchar(50) DEFAULT NULL,
                PRIMARY KEY (`id_profile`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;";
            
            $pdo->exec($sql);
            

            $sql = "INSERT INTO `profile` (`nom_profile`, `permissions`, `user_cre`) 
                   VALUES ('admin', '*', 'system')";
            $pdo->exec($sql);
        }
    } catch (Exception $e) {
        throw new Exception("Failed to create profile table: " . $e->getMessage());
    }
}

function logError($message) {
    $logFile = __DIR__ . '/import_errors.log';
    $timestamp = date('Y-m-d H:i:s');
    error_log("[$timestamp] $message\n", 3, $logFile);
}

function importSQL($pdo, $content) {
    try {

        $pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, 0);
        $pdo->exec('SET FOREIGN_KEY_CHECKS=0');
        

        checkAndCreateProfileTable($pdo);
        

        $content = str_replace(["\r\n", "\r"], "\n", $content);
        $queries = explode(";\n", $content);
        
        foreach ($queries as $query) {
            $query = trim($query);
            if (empty($query)) continue;
            

            if (preg_match('/^--/', $query) || empty(trim($query))) {
                continue;
            }
            
            try {
                $result = $pdo->exec($query);
                if ($result === false) {
                    $error = $pdo->errorInfo();

                    if ($error[1] !== 1050) {
                        logError("Query failed: " . $error[2] . "\nQuery: " . $query);
                        throw new Exception($error[2]);
                    }
                }
            } catch (PDOException $e) {

                if ($e->errorInfo[1] !== 1050) {
                    throw $e;
                }
            }
        }
        

        $pdo->exec('SET FOREIGN_KEY_CHECKS=1');
        

        $pdo->exec('COMMIT');
        

        $pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, 1);
        
        return true;
    } catch (Exception $e) {
        try {

            $pdo->exec('ROLLBACK');
        } catch (Exception $rollbackError) {
            logError("Rollback failed: " . $rollbackError->getMessage());
        }
        
        try {

            $pdo->exec('SET FOREIGN_KEY_CHECKS=1');
        } catch (Exception $fkError) {
            logError("Failed to reset foreign key checks: " . $fkError->getMessage());
        }
        
        try {

            $pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, 1);
        } catch (Exception $acError) {
            logError("Failed to restore autocommit: " . $acError->getMessage());
        }
        
        throw $e;
    }
}

try {

    if (!isset($_FILES['database']) || $_FILES['database']['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('No file uploaded or upload failed');
    }

    $file = $_FILES['database'];
    

    if ($file['size'] > 50 * 1024 * 1024) {
        throw new Exception('File size exceeds limit (50MB)');
    }


    $format = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if ($format !== 'sql') {
        throw new Exception('Invalid file format. Only SQL files are supported.');
    }


    $content = file_get_contents($file['tmp_name']);
    if ($content === false) {
        throw new Exception('Failed to read uploaded file');
    }


    if (substr($content, 0, 3) === "\xEF\xBB\xBF") {
        $content = substr($content, 3);
    }


    connect();
    global $pdo;


    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


    $success = importSQL($pdo, $content);

    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'message' => 'Database imported successfully',
        'filename' => $file['name']
    ]);

} catch (Exception $e) {
    logError("Import error: " . $e->getMessage());
    
    header('HTTP/1.1 500 Internal Server Error');
    header('Content-Type: application/json');
    echo json_encode([
        'error' => $e->getMessage(),
        'details' => 'Check server logs for more information'
    ]);
} finally {
    if (isset($pdo)) {
        try {
            $pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, 1);
            $pdo->exec('SET FOREIGN_KEY_CHECKS=1');
        } catch (Exception $e) {
            logError("Cleanup failed: " . $e->getMessage());
        }
        disconnect();
    }
}
?>