<?php
/**
 * ===================================================================================
 * Core Configuration File (PRODUCTION READY)
 * ===================================================================================
 * This final version has the license verification system re-enabled and encrypted.
 */

// Start the PHP Session at the absolute beginning of the script.
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// --- 1. Enable Error Reporting (Good for development, can be set to 0 for a live site) ---
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// --- 2. Define Core Application Paths & URLs ---
define('APP_ROOT', __DIR__);
define('BASE_URL', 'http://school.e-cars.co.ke/homework_portal');

// --- 3. License & Security Keys ---
define('SERVER_KEY', 'hw-portal-eict-A3B7-X9Z1-K4L2'); // Master application key
define('ENCRYPTION_KEY', 'd#f$Vv2@qZ9pL7!aG5sR8bK4nC1jM6eG'); // Your secret encryption password
define('ENCRYPTION_METHOD', 'aes-256-cbc');

// --- 4. Database Connection ---
$db_host = 'localhost';
$db_name = 'ecarscok_school';
$db_user = 'ecarscok_school';
$db_pass = 'Elizabethb5714!!';
$charset = 'utf8mb4';

$dsn = "mysql:host=$db_host;dbname=$db_name;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
    $pdo = new PDO($dsn, $db_user, $db_pass, $options);
} catch (\PDOException $e) {
    throw new \PDOException($e->getMessage(), (int)$e->getCode());
}

// --- 5. Global Helper Functions ---
function e(?string $string): string
{
    return htmlspecialchars($string ?? '', ENT_QUOTES, 'UTF-8');
}

// ===============================================================
// ** NEW: Hardened & Encrypted License Verification Function **
// ===============================================================
function verify_license() {
    $license_file_path = APP_ROOT . '/license.key';

    if (!file_exists($license_file_path)) {
        die("FATAL ERROR: License key file (license.key) not found. Application cannot start.");
    }

    $encrypted_content = file_get_contents($license_file_path);
    if (empty($encrypted_content)) {
        die("FATAL ERROR: License file is empty. Please contact support.");
    }

    $decoded_content = base64_decode($encrypted_content);
    // Use an error suppressor with explode as it can throw a notice on malformed data
    list($iv, $encrypted_data) = @explode('::', $decoded_content, 2);

    if (!$iv || !$encrypted_data) {
        die("FATAL ERROR: Invalid license file format. Please contact support.");
    }

    $decrypted_json = openssl_decrypt($encrypted_data, ENCRYPTION_METHOD, ENCRYPTION_KEY, 0, $iv);

    if ($decrypted_json === false) {
        die("FATAL ERROR: License decryption failed. The license key may be corrupt or invalid.");
    }

    $license_details = json_decode($decrypted_json, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        die("FATAL ERROR: License data is corrupt.");
    }

    // 1. Check if the master key matches
    if (!isset($license_details['license_key']) || $license_details['license_key'] !== SERVER_KEY) {
        die("FATAL ERROR: Invalid license key signature.");
    }

    // 2. Check if the current domain is allowed
    // Using $_SERVER['HTTP_HOST'] is generally more reliable than SERVER_NAME
    $current_domain = $_SERVER['HTTP_HOST'];
    if (!isset($license_details['allowed_domains']) || !in_array($current_domain, $license_details['allowed_domains'])) {
        die("FATAL ERROR: This domain ({$current_domain}) is not authorized to run this application.");
    }
    
    return true;
}

// --- Run the license check on every page load.
verify_license();
?>
