<?php
/**
 * Safe MySQL PDO Connection Configuration File
 * B2B Garments Marketplace
 */

// Load database environment variables or fallback to safe defaults
define('DB_HOST', getenv('DB_HOST') ?: 'localhost');
define('DB_PORT', getenv('DB_PORT') ?: '3306');
define('DB_NAME', getenv('DB_NAME') ?: 'b2b_marketplace');
define('DB_USER', getenv('DB_USER') ?: 'root');
define('DB_PASS', getenv('DB_PASS') ?: '');

class Database {
    private static $instance = null;

    /**
     * Get the singular safe PDO instance (Singleton Pattern)
     * @return PDO
     */
    public static function getConnection() {
        if (self::$instance === null) {
            try {
                $dsn = "mysql:host=" . DB_HOST . ";port=" . DB_PORT . ";dbname=" . DB_NAME . ";charset=utf8mb4";
                $options = [
                    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES   => false,
                    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci"
                ];
                
                self::$instance = new PDO($dsn, DB_USER, DB_PASS, $options);
                
                // Automatic schema migration for order analysis transaction features
                try {
                    self::$instance->exec("ALTER TABLE sourcing_orders ADD COLUMN IF NOT EXISTS garment_item VARCHAR(150) NULL");
                    self::$instance->exec("ALTER TABLE sourcing_orders ADD COLUMN IF NOT EXISTS order_number VARCHAR(100) NULL UNIQUE");
                    self::$instance->exec("ALTER TABLE sourcing_orders ADD COLUMN IF NOT EXISTS shipment_status VARCHAR(50) NOT NULL DEFAULT 'Pending'");
                    self::$instance->exec("ALTER TABLE sourcing_orders ADD COLUMN IF NOT EXISTS payment_status VARCHAR(50) NOT NULL DEFAULT 'Pending'");
                    self::$instance->exec("ALTER TABLE sourcing_orders ADD COLUMN IF NOT EXISTS production_status VARCHAR(50) NOT NULL DEFAULT 'Pending'");
                    self::$instance->exec("ALTER TABLE sourcing_orders ADD COLUMN IF NOT EXISTS completed_at TIMESTAMP NULL");

                    self::$instance->exec("ALTER TABLE capacity_posts ADD COLUMN IF NOT EXISTS garment_item VARCHAR(150) NULL");
                    self::$instance->exec("ALTER TABLE capacity_posts ADD COLUMN IF NOT EXISTS order_number VARCHAR(100) NULL UNIQUE");
                    self::$instance->exec("ALTER TABLE capacity_posts ADD COLUMN IF NOT EXISTS shipment_status VARCHAR(50) NOT NULL DEFAULT 'Pending'");
                    self::$instance->exec("ALTER TABLE capacity_posts ADD COLUMN IF NOT EXISTS payment_status VARCHAR(50) NOT NULL DEFAULT 'Pending'");
                    self::$instance->exec("ALTER TABLE capacity_posts ADD COLUMN IF NOT EXISTS production_status VARCHAR(50) NOT NULL DEFAULT 'Pending'");
                    self::$instance->exec("ALTER TABLE capacity_posts ADD COLUMN IF NOT EXISTS completed_at TIMESTAMP NULL");

                    self::$instance->exec("ALTER TABLE capacity_quotes ADD COLUMN IF NOT EXISTS style_name VARCHAR(255) NULL");
                    self::$instance->exec("ALTER TABLE capacity_quotes ADD COLUMN IF NOT EXISTS smv DECIMAL(8,2) NULL");
                    self::$instance->exec("ALTER TABLE capacity_quotes ADD COLUMN IF NOT EXISTS sample_photos_json TEXT NULL");
                    self::$instance->exec("ALTER TABLE capacity_quotes ADD COLUMN IF NOT EXISTS spec_description TEXT NULL");
                } catch (Exception $schemaEx) {
                    // Ignore column already exists or other schema update warnings
                }
            } catch (PDOException $e) {
                // Return a clean error message without exposing database credentials in stack traces
                http_response_code(500);
                header('Content-Type: application/json');
                echo json_encode([
                    "success" => false,
                    "error" => "Database connection failure. Please verify configuration.",
                    "details" => $e->getMessage()
                ]);
                exit();
            }
        }
        return self::$instance;
    }
}

// Start PHP session securely if not already active
if (session_status() === PHP_SESSION_NONE) {
    // Enable secure session cookie settings
    ini_set('session.cookie_httponly', 1);
    ini_set('session.use_only_cookies', 1);
    ini_set('session.cookie_samesite', 'Strict');
    
    // Set secure cookie flag if running over HTTPS
    if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
         ini_set('session.cookie_secure', 1);
    }
    
    session_start();
}

/**
 * Utility: Checks if a user is logged in
 * @return array|null Returns user data array or null
 */
function getLoggedInUser() {
    if (isset($_SESSION['user_id'])) {
        return [
            'id' => $_SESSION['user_id'],
            'name' => $_SESSION['user_name'],
            'email' => $_SESSION['user_email'],
            'role' => $_SESSION['user_role'],
            'designation' => $_SESSION['user_designation'] ?? $_SESSION['user_role']
        ];
    }
    return null;
}

/**
 * Utility: Require authentication to proceed
 */
function requireLogin() {
    if (!isset($_SESSION['user_id'])) {
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
            http_response_code(401);
            echo json_encode(["success" => false, "error" => "Authentication required"]);
            exit();
        } else {
            header("Location: /auth/login.php");
            exit();
        }
    }
}
