<?php
/**
 * Database Configuration
 * 
 * This file contains database connection settings and PDO initialization.
 * For security, this file should be placed outside the web root in production.
 */

// Database configuration
$dbConfig = [
    'host' => 'localhost',
    'dbname' => 'finggu_finggunewdash',  // Replace with your database name
    'username' => 'finggu_finggunewdash',  // Replace with your database username
    'password' => 'Bunty@123',  // Replace with your database password
    'charset' => 'utf8mb4',
    'options' => [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
        PDO::ATTR_PERSISTENT         => false,
    ],
];

// Error reporting for development
error_reporting(E_ALL);
ini_set('display_errors', '1');

// Set timezone
date_default_timezone_set('Asia/Kolkata');

// Initialize PDO
try {
    $dsn = "mysql:host={$dbConfig['host']};dbname={$dbConfig['dbname']};charset={$dbConfig['charset']}";
    $pdo = new PDO(
        $dsn,
        $dbConfig['username'],
        $dbConfig['password'],
        $dbConfig['options']
    );
} catch (PDOException $e) {
    // Log the error details
    error_log("Database Connection Error: " . $e->getMessage());
    
    // Display a generic error message
    if (strpos($_SERVER['REQUEST_URI'], '/admin/') !== false) {
        // If in admin area, show a maintenance page
        header('HTTP/1.1 503 Service Unavailable');
        include __DIR__ . '/../maintenance.php';
    } else {
        // For frontend, redirect to home with error flag
        header('Location: /?error=database');
    }
    exit();
}

// Include the security class
require_once __DIR__ . '/Security.php';

// Start session with security measures
Security::startSession();

// Function to safely execute SQL files
function executeSQLFile($pdo, $file) {
    if (!file_exists($file)) {
        throw new Exception("SQL file not found: $file");
    }
    
    $queries = file_get_contents($file);
    
    // Split the SQL file into individual queries
    $queries = explode(';', $queries);
    
    // Execute each query
    foreach ($queries as $query) {
        $query = trim($query);
        if (!empty($query)) {
            try {
                $pdo->exec($query);
            } catch (PDOException $e) {
                // Skip duplicate table errors
                if ($e->getCode() !== '42S01') { // Table already exists
                    throw $e;
                }
            }
        }
    }
}

// Check if we need to run database migrations
$migrationFile = __DIR__ . '/../migrations/migration.lock';
if (!file_exists($migrationFile)) {
    try {
        // Create migrations directory if it doesn't exist
        if (!is_dir(__DIR__ . '/../migrations')) {
            mkdir(__DIR__ . '/../migrations', 0755, true);
        }
        
        // Run the initial database setup
        executeSQLFile($pdo, __DIR__ . '/../sql/create_admin_tables.sql');
        
        // Create a lock file to prevent running migrations again
        file_put_contents($migrationFile, date('Y-m-d H:i:s') . " - Initial database setup completed\n");
        
    } catch (Exception $e) {
        error_log("Database Migration Error: " . $e->getMessage());
        // Don't stop execution if migration fails
    }
}

// Global helper functions
function sanitize($data) {
    return Security::sanitizeInput($data);
}

function csrf_token($formName = 'default') {
    return Security::generateCSRFToken($formName);
}

function csrf_field($formName = 'default') {
    $token = csrf_token($formName);
    return "<input type=\"hidden\" name=\"csrf_token\" value=\"$token\">";
}

function validate_csrf($formName = 'default', $token = null) {
    $token = $token ?? ($_POST['csrf_token'] ?? '');
    return Security::verifyCSRFToken($formName, $token);
}

// Set error handler
set_error_handler(function($errno, $errstr, $errfile, $errline) {
    if (!(error_reporting() & $errno)) {
        // This error code is not included in error_reporting
        return false;
    }
    
    $errorType = [
        E_ERROR => 'Error',
        E_WARNING => 'Warning',
        E_PARSE => 'Parse Error',
        E_NOTICE => 'Notice',
        E_CORE_ERROR => 'Core Error',
        E_CORE_WARNING => 'Core Warning',
        E_COMPILE_ERROR => 'Compile Error',
        E_COMPILE_WARNING => 'Compile Warning',
        E_USER_ERROR => 'User Error',
        E_USER_WARNING => 'User Warning',
        E_USER_NOTICE => 'User Notice',
        E_STRICT => 'Strict Standards',
        E_RECOVERABLE_ERROR => 'Recoverable Error',
        E_DEPRECATED => 'Deprecated',
        E_USER_DEPRECATED => 'User Deprecated',
    ][$errno] ?? 'Unknown Error';
    
    $message = sprintf(
        '%s: %s in %s on line %s',
        $errorType,
        $errstr,
        str_replace($_SERVER['DOCUMENT_ROOT'], '', $errfile),
        $errline
    );
    
    // Log the error
    error_log($message);
    
    // Don't execute PHP internal error handler
    return true;
});

// Set exception handler
set_exception_handler(function($e) {
    error_log("Uncaught Exception: " . $e->getMessage() . " in " . $e->getFile() . ":" . $e->getLine());
    
    if (strpos($_SERVER['REQUEST_URI'], '/admin/') !== false) {
        // In admin area, show error page
        header('HTTP/1.1 500 Internal Server Error');
        include __DIR__ . '/../error.php';
    } else {
        // On frontend, show generic error
        header('HTTP/1.1 500 Internal Server Error');
        echo '<h1>Something went wrong</h1>';
        echo '<p>Our team has been notified about this issue.</p>';
    }
    exit(1);
});

// Set shutdown function to catch fatal errors
register_shutdown_function(function() {
    $error = error_get_last();
    
    if ($error !== null && in_array($error['type'], [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR])) {
        error_log(sprintf(
            'Fatal error: %s in %s on line %s',
            $error['message'],
            str_replace($_SERVER['DOCUMENT_ROOT'], '', $error['file']),
            $error['line']
        ));
        
        if (strpos($_SERVER['REQUEST_URI'], '/admin/') !== false) {
            header('HTTP/1.1 500 Internal Server Error');
            include __DIR__ . '/../error.php';
        } else {
            header('HTTP/1.1 500 Internal Server Error');
            echo '<h1>Something went wrong</h1>';
            echo '<p>Our team has been notified about this issue.</p>';
        }
    }
});
