<?php
// ============================================
// NEXUS IT - Configuration File (Complete)
// ============================================

// Error reporting (disable in production)
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

// Session configuration
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_secure', 0);
ini_set('session.use_strict_mode', 1);
session_start();

// ============================================
// DATABASE CONFIGURATION
// ============================================
define('DB_HOST', 'localhost');
define('DB_NAME', 'escal_esc');
define('DB_USER', 'escal_esc');
define('DB_PASS', 'Bkasxh12.');
define('DB_CHARSET', 'utf8mb4');

// ============================================
// SITE CONFIGURATION
// ============================================
define('SITE_URL', 'https://esc.al');
define('SITE_NAME', 'Esc.al');
define('ADMIN_EMAIL', 'admin@nexusit.com');

// ============================================
// UPLOAD CONFIGURATION
// ============================================
define('UPLOAD_DIR', __DIR__ . '/uploads/');
define('MAX_UPLOAD_SIZE', 5 * 1024 * 1024);
define('ALLOWED_EXTENSIONS', ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg']);
define('ALLOWED_MIMES', [
    'image/jpeg',
    'image/png', 
    'image/gif',
    'image/webp',
    'image/svg+xml'
]);

// ============================================
// TIMEZONE
// ============================================
date_default_timezone_set('Europe/Tirane');

// ============================================
// CREATE UPLOAD DIRECTORY IF NOT EXISTS
// ============================================
if (!is_dir(UPLOAD_DIR)) {
    mkdir(UPLOAD_DIR, 0755, true);
    file_put_contents(UPLOAD_DIR . '.htaccess', "Options -Indexes\nAllow from all");
    file_put_contents(UPLOAD_DIR . 'index.php', '<?php // Silence is golden');
}

// Create subdirectories
$subdirs = ['services', 'projects', 'why', 'hero', 'logo', 'contact'];
foreach ($subdirs as $subdir) {
    if (!is_dir(UPLOAD_DIR . $subdir)) {
        mkdir(UPLOAD_DIR . $subdir, 0755, true);
    }
}

// ============================================
// DATABASE CONNECTION
// ============================================
try {
    $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET;
    $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"
    ];
    $pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
} catch (PDOException $e) {
    error_log("Database Connection Error: " . $e->getMessage());
    die("Database connection failed. Please try again later.");
}

// ============================================
// HELPER FUNCTIONS
// ============================================

function getSetting($key, $lang = 'en') {
    global $pdo;
    try {
        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ? AND lang = ? LIMIT 1");
        $stmt->execute([$key, $lang]);
        $result = $stmt->fetch();
        return $result ? $result['setting_value'] : '';
    } catch (PDOException $e) {
        error_log("getSetting Error: " . $e->getMessage());
        return '';
    }
}

function getAllSettings($lang = 'en') {
    global $pdo;
    try {
        $stmt = $pdo->prepare("SELECT setting_key, setting_value FROM settings WHERE lang = ?");
        $stmt->execute([$lang]);
        return $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    } catch (PDOException $e) {
        error_log("getAllSettings Error: " . $e->getMessage());
        return [];
    }
}

function updateSetting($key, $value, $lang = 'en') {
    global $pdo;
    try {
        $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value, lang) VALUES (?, ?, ?) 
                               ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
        return $stmt->execute([$key, $value, $lang]);
    } catch (PDOException $e) {
        error_log("updateSetting Error: " . $e->getMessage());
        return false;
    }
}

function isLoggedIn() {
    return isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true;
}

function requireLogin() {
    if (!isLoggedIn()) {
        header('Location: login.php');
        exit();
    }
}

function sanitize($data) {
    return htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
}

function redirect($url) {
    header("Location: $url");
    exit();
}

function getServices() {
    global $pdo;
    try {
        $stmt = $pdo->prepare("SELECT * FROM services WHERE is_active = 1 ORDER BY sort_order ASC");
        $stmt->execute();
        return $stmt->fetchAll();
    } catch (PDOException $e) {
        error_log("getServices Error: " . $e->getMessage());
        return [];
    }
}

function getProjects() {
    global $pdo;
    try {
        $stmt = $pdo->prepare("SELECT * FROM projects WHERE is_active = 1 ORDER BY sort_order ASC");
        $stmt->execute();
        return $stmt->fetchAll();
    } catch (PDOException $e) {
        error_log("getProjects Error: " . $e->getMessage());
        return [];
    }
}

function getWhyItems() {
    global $pdo;
    try {
        $stmt = $pdo->prepare("SELECT * FROM why_items WHERE is_active = 1 ORDER BY sort_order ASC");
        $stmt->execute();
        return $stmt->fetchAll();
    } catch (PDOException $e) {
        error_log("getWhyItems Error: " . $e->getMessage());
        return [];
    }
}

function saveMessage($data) {
    global $pdo;
    try {
        $stmt = $pdo->prepare("INSERT INTO messages (first_name, last_name, email, company, service, message) VALUES (?, ?, ?, ?, ?, ?)");
        return $stmt->execute([
            $data['first_name'],
            $data['last_name'],
            $data['email'],
            $data['company'] ?? '',
            $data['service'] ?? '',
            $data['message']
        ]);
    } catch (PDOException $e) {
        error_log("saveMessage Error: " . $e->getMessage());
        return false;
    }
}

function getUnreadMessagesCount() {
    global $pdo;
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM messages WHERE is_read = 0");
        $stmt->execute();
        return $stmt->fetchColumn();
    } catch (PDOException $e) {
        error_log("getUnreadMessagesCount Error: " . $e->getMessage());
        return 0;
    }
}

// ============================================
// FILE UPLOAD FUNCTIONS
// ============================================

function uploadFile($file, $subdir = '', $prefix = 'img_') {
    if (!isset($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) {
        return ['success' => false, 'error' => 'No file uploaded'];
    }
    
    if ($file['error'] !== UPLOAD_ERR_OK) {
        $errorMessages = [
            UPLOAD_ERR_INI_SIZE => 'File too large',
            UPLOAD_ERR_FORM_SIZE => 'File too large',
            UPLOAD_ERR_PARTIAL => 'File was only partially uploaded',
            UPLOAD_ERR_NO_FILE => 'No file was uploaded',
            UPLOAD_ERR_NO_TMP_DIR => 'Missing temporary folder',
            UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk',
            UPLOAD_ERR_EXTENSION => 'Upload stopped by extension'
        ];
        $error = $errorMessages[$file['error']] ?? 'Unknown upload error';
        return ['success' => false, 'error' => $error];
    }
    
    if ($file['size'] > MAX_UPLOAD_SIZE) {
        return ['success' => false, 'error' => 'File too large. Max 5MB'];
    }
    
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, ALLOWED_EXTENSIONS)) {
        return ['success' => false, 'error' => 'Invalid file type. Allowed: ' . implode(', ', ALLOWED_EXTENSIONS)];
    }
    
    $targetDir = UPLOAD_DIR;
    if (!empty($subdir)) {
        $targetDir .= $subdir . '/';
        if (!is_dir($targetDir)) {
            mkdir($targetDir, 0755, true);
        }
    }
    
    $filename = $prefix . bin2hex(random_bytes(8)) . '.' . $ext;
    $destination = $targetDir . $filename;
    
    if (move_uploaded_file($file['tmp_name'], $destination)) {
        chmod($destination, 0644);
        $relativePath = 'uploads/' . ($subdir ? $subdir . '/' : '') . $filename;
        return ['success' => true, 'path' => $relativePath];
    }
    
    return ['success' => false, 'error' => 'Failed to save file'];
}

function deleteUploadedFile($path) {
    if (empty($path)) return false;
    
    $fullPath = __DIR__ . '/' . $path;
    $uploadDir = realpath(UPLOAD_DIR);
    $realPath = realpath($fullPath);
    
    if ($realPath === false || strpos($realPath, $uploadDir) !== 0) {
        return false;
    }
    
    if (file_exists($fullPath) && is_file($fullPath)) {
        return unlink($fullPath);
    }
    return false;
}

// ============================================
// SITE LOGO FUNCTIONS (with size support)
// ============================================

function getSiteLogo() {
    global $pdo;
    try {
        $stmt = $pdo->query("SHOW TABLES LIKE 'site_logo'");
        if ($stmt->rowCount() === 0) {
            $pdo->exec("CREATE TABLE IF NOT EXISTS `site_logo` (
                `id` int(11) NOT NULL AUTO_INCREMENT,
                `logo_path` varchar(255) NOT NULL,
                `footer_logo_path` varchar(255) DEFAULT '',
                `updated_at` timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
            $pdo->exec("INSERT INTO `site_logo` (`logo_path`, `footer_logo_path`) VALUES ('', '')");
        }
        
        $stmt = $pdo->query("SELECT logo_path FROM site_logo ORDER BY id DESC LIMIT 1");
        $result = $stmt->fetch();
        return $result ? $result['logo_path'] : '';
    } catch (PDOException $e) {
        error_log("getSiteLogo Error: " . $e->getMessage());
        return '';
    }
}

function updateSiteLogo($path) {
    global $pdo;
    try {
        $stmt = $pdo->prepare("UPDATE site_logo SET logo_path = ? WHERE id = 1");
        return $stmt->execute([$path]);
    } catch (PDOException $e) {
        error_log("updateSiteLogo Error: " . $e->getMessage());
        return false;
    }
}

function getFooterLogo() {
    global $pdo;
    try {
        $stmt = $pdo->query("SELECT footer_logo_path FROM site_logo ORDER BY id DESC LIMIT 1");
        $result = $stmt->fetch();
        return $result ? $result['footer_logo_path'] : '';
    } catch (PDOException $e) {
        error_log("getFooterLogo Error: " . $e->getMessage());
        return '';
    }
}

function updateFooterLogo($path) {
    global $pdo;
    try {
        $stmt = $pdo->prepare("UPDATE site_logo SET footer_logo_path = ? WHERE id = 1");
        return $stmt->execute([$path]);
    } catch (PDOException $e) {
        error_log("updateFooterLogo Error: " . $e->getMessage());
        return false;
    }
}

function getLogoSize() {
    $size = getSetting('logo_size', 'en');
    return !empty($size) ? $size : '40';
}

function getFooterLogoSize() {
    $size = getSetting('footer_logo_size', 'en');
    return !empty($size) ? $size : '35';
}

// ============================================
// HERO BACKGROUND FUNCTIONS
// ============================================

function getHeroBackground() {
    return getSetting('hero_background', 'en');
}

function updateHeroBackground($path) {
    return updateSetting('hero_background', $path, 'en');
}

// ============================================
// CONTACT ICONS FUNCTIONS
// ============================================

function getContactIcons() {
    return [
        'email_icon' => getSetting('contact_email_icon', 'en'),
        'phone_icon' => getSetting('contact_phone_icon', 'en'),
        'location_icon' => getSetting('contact_location_icon', 'en'),
        'support_icon' => getSetting('contact_support_icon', 'en')
    ];
}

function updateContactIcon($key, $value) {
    return updateSetting($key, $value, 'en');
}

// ============================================
// WHY ITEMS IMAGE FUNCTIONS
// ============================================

function getWhyImage($id) {
    global $pdo;
    try {
        $stmt = $pdo->prepare("SELECT image FROM why_items WHERE id = ?");
        $stmt->execute([$id]);
        $result = $stmt->fetch();
        return $result ? $result['image'] : '';
    } catch (PDOException $e) {
        return '';
    }
}

function updateWhyImage($id, $path) {
    global $pdo;
    try {
        $stmt = $pdo->prepare("UPDATE why_items SET image = ? WHERE id = ?");
        return $stmt->execute([$path, $id]);
    } catch (PDOException $e) {
        return false;
    }
}

// ============================================
// BACKUP FUNCTION
// ============================================

function backupSettings() {
    global $pdo;
    try {
        $settings = $pdo->query("SELECT * FROM settings")->fetchAll();
        if (!is_dir(__DIR__ . '/backups')) {
            mkdir(__DIR__ . '/backups', 0755, true);
        }
        $backupFile = __DIR__ . '/backups/settings_backup_' . date('Y-m-d_H-i-s') . '.json';
        file_put_contents($backupFile, json_encode($settings, JSON_PRETTY_PRINT));
        return true;
    } catch (Exception $e) {
        error_log("backupSettings Error: " . $e->getMessage());
        return false;
    }
}

// ============================================
// INITIALIZE DATABASE TABLES IF NOT EXISTS
// ============================================

function initDatabaseTables() {
    global $pdo;
    
    // Create site_logo table if not exists
    $pdo->exec("CREATE TABLE IF NOT EXISTS `site_logo` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `logo_path` varchar(255) NOT NULL,
        `footer_logo_path` varchar(255) DEFAULT '',
        `updated_at` timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    
    // Insert default row if empty
    $stmt = $pdo->query("SELECT COUNT(*) FROM site_logo");
    if ($stmt->fetchColumn() == 0) {
        $pdo->exec("INSERT INTO `site_logo` (`logo_path`, `footer_logo_path`) VALUES ('', '')");
    }
    
    // Add image column to why_items if not exists
    try {
        $pdo->exec("ALTER TABLE `why_items` ADD COLUMN `image` varchar(255) DEFAULT NULL AFTER `icon`");
    } catch (PDOException $e) {
        // Column might already exist - ignore error
    }
    
    // Insert default settings for contact icons if not exists
    $icons = ['contact_email_icon', 'contact_phone_icon', 'contact_location_icon', 'contact_support_icon'];
    foreach ($icons as $icon) {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM settings WHERE setting_key = ? AND lang = 'en'");
        $stmt->execute([$icon]);
        if ($stmt->fetchColumn() == 0) {
            $defaultIcon = $icon == 'contact_email_icon' ? '📧' : ($icon == 'contact_phone_icon' ? '📞' : ($icon == 'contact_location_icon' ? '📍' : '🕐'));
            $pdo->prepare("INSERT INTO settings (setting_key, setting_value, lang) VALUES (?, ?, 'en')")->execute([$icon, $defaultIcon]);
            $pdo->prepare("INSERT INTO settings (setting_key, setting_value, lang) VALUES (?, ?, 'it')")->execute([$icon, $defaultIcon]);
        }
    }
    
    // Insert hero background setting if not exists
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM settings WHERE setting_key = 'hero_background' AND lang = 'en'");
    $stmt->execute();
    if ($stmt->fetchColumn() == 0) {
        $pdo->prepare("INSERT INTO settings (setting_key, setting_value, lang) VALUES ('hero_background', '', 'en')")->execute();
        $pdo->prepare("INSERT INTO settings (setting_key, setting_value, lang) VALUES ('hero_background', '', 'it')")->execute();
    }
    
    // Insert logo size settings if not exists
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM settings WHERE setting_key = 'logo_size' AND lang = 'en'");
    $stmt->execute();
    if ($stmt->fetchColumn() == 0) {
        $pdo->prepare("INSERT INTO settings (setting_key, setting_value, lang) VALUES ('logo_size', '40', 'en')")->execute();
        $pdo->prepare("INSERT INTO settings (setting_key, setting_value, lang) VALUES ('footer_logo_size', '35', 'en')")->execute();
    }
}

// Run initialization
initDatabaseTables();
?>