<?php
/**
 * SMM Paket Satış Scripti
 * Ana Konfigürasyon Dosyası
 * @version 1.0.1
 */

// Hata Raporlama
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Session
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Zaman Dilimi
date_default_timezone_set('Europe/Istanbul');

// Sabitler
define('SITE_VERSION', '1.0.1');

// ==================== IYZICO SDK YÜKLEME (MANUEL) ====================
$iyzicoBootstrap = __DIR__ . '/iyzipay-php/IyzipayBootstrap.php';
if (file_exists($iyzicoBootstrap)) {
    require_once $iyzicoBootstrap;
    \IyzipayBootstrap::init();
    define('IYZICO_SDK_LOADED', true);
} else {
    define('IYZICO_SDK_LOADED', false);
}
// =====================================================================

// Veritabanı Ayarları
define('DB_HOST', 'localhost');
define('DB_NAME', 'qqqlgaig_dijiyazilim');
define('DB_USER', 'qqqlgaig_dijiyazilim');
define('DB_PASS', 'Şifreniz');
define('DB_CHARSET', 'utf8mb4');

// Veritabanı Bağlantısı
class Database {
    private static $instance = null;
    private $pdo;

    private function __construct() {
        try {
            $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET;
            $this->pdo = new PDO($dsn, DB_USER, DB_PASS, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false
            ]);
        } catch (PDOException $e) {
            die("Veritabanı hatası: " . $e->getMessage());
        }
    }

    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function getConnection() {
        return $this->pdo;
    }
}

// Ayarlar Sınıfı
class Settings {
    private $db;
    private $settings = [];
    private $themes = [];
    private static $instance = null;

    public function __construct() {
        $this->db = Database::getInstance()->getConnection();
        $this->loadSettings();
        $this->loadThemes();
    }

    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function loadSettings() {
        try {
            $stmt = $this->db->query("SELECT setting_key, setting_value, setting_type FROM settings");
            while ($row = $stmt->fetch()) {
                $value = $row['setting_value'];
                if ($row['setting_type'] === 'int') $value = (int) $value;
                elseif ($row['setting_type'] === 'bool') $value = (bool) $value;
                elseif ($row['setting_type'] === 'json') $value = json_decode($value, true);
                $this->settings[$row['setting_key']] = $value;
            }
        } catch (PDOException $e) {
            $this->settings = $this->getDefaults();
        }
    }

    private function loadThemes() {
        try {
            $stmt = $this->db->query("SELECT * FROM themes WHERE is_active = 1 ORDER BY sort_order ASC");
            while ($row = $stmt->fetch()) {
                $this->themes[$row['id']] = $row;
            }
        } catch (PDOException $e) {
            $this->themes = [];
        }
    }

    private function getDefaults() {
        return [
            'site_url' => 'http://localhost',
            'site_name' => 'SocialBoost',
            'site_title' => 'SocialBoost - Sosyal Medya Paketleri',
            'site_description' => 'Uygun fiyatlı sosyal medya paketleri',
            'site_logo' => '',
            'site_favicon' => '',
            'active_theme_id' => 1,
            'contact_email' => 'info@site.com',
            'contact_phone' => '+90 555 555 55 55',
            'whatsapp_number' => '+905555555555',
            'currency_symbol' => '₺',
            'maintenance_mode' => 0,
            'footer_text' => '© 2026 Tüm hakları saklıdır.'
        ];
    }

    public function get($key, $default = null) {
        return $this->settings[$key] ?? $default;
    }

    public function getAll() {
        return $this->settings;
    }

    public function getThemes() {
        return $this->themes;
    }

    public function getActiveTheme() {
        $id = $this->get('active_theme_id', 1);
        return $this->themes[$id] ?? [
            'id' => 1,
            'name' => 'Modern Dark',
            'folder' => 'modern-dark',
            'primary_color' => '#6366f1',
            'secondary_color' => '#8b5cf6',
            'accent_color' => '#22d3ee',
            'background_color' => '#0f172a',
            'text_color' => '#f8fafc',
            'is_dark' => 1
        ];
    }

    public function getSiteUrl() {
        return rtrim($this->get('site_url', ''), '/');
    }

    public function getLogoUrl() {
        $logo = $this->get('site_logo');
        if (empty($logo)) return null;
        if (filter_var($logo, FILTER_VALIDATE_URL)) return $logo;
        return $this->getSiteUrl() . '/' . ltrim($logo, '/');
    }

    public function getFaviconUrl() {
        $favicon = $this->get('site_favicon');
        if (empty($favicon)) return null;
        if (filter_var($favicon, FILTER_VALIDATE_URL)) return $favicon;
        return $this->getSiteUrl() . '/' . ltrim($favicon, '/');
    }
}

// Yardımcı Fonksiyonlar
function clean($data) {
    if (is_array($data)) return array_map('clean', $data);
    return htmlspecialchars(trim($data), ENT_QUOTES, 'UTF-8');
}

function generateCSRFToken() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function validateCSRFToken($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

function isLoggedIn() {
    return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}

function isAdmin() {
    return isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin';
}

function formatMoney($amount) {
    global $settings;
    $symbol = $settings->get('currency_symbol', '₺');
    return $symbol . number_format((float)$amount, 2, ',', '.');
}

function formatDate($date) {
    return date('d.m.Y H:i', strtotime($date));
}

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

function setFlash($type, $message) {
    $_SESSION['flash'] = ['type' => $type, 'message' => $message];
}

function getFlash() {
    if (isset($_SESSION['flash'])) {
        $flash = $_SESSION['flash'];
        unset($_SESSION['flash']);
        return $flash;
    }
    return null;
}

function generateOrderNumber() {
    return 'SP' . date('Ymd') . strtoupper(substr(uniqid(), -6));
}

function getClientIP() {
    $keys = ['HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'REMOTE_ADDR'];
    foreach ($keys as $key) {
        if (!empty($_SERVER[$key])) {
            $ip = explode(',', $_SERVER[$key])[0];
            if (filter_var(trim($ip), FILTER_VALIDATE_IP)) return trim($ip);
        }
    }
    return '0.0.0.0';
}

function hexToRgb($hex) {
    $hex = ltrim($hex, '#');
    return hexdec(substr($hex,0,2)) . ',' . hexdec(substr($hex,2,2)) . ',' . hexdec(substr($hex,4,2));
}

// Global Objeler
$db = Database::getInstance()->getConnection();
$settings = Settings::getInstance();
$theme = $settings->getActiveTheme();

define('SITE_URL', $settings->getSiteUrl());
define('SITE_NAME', $settings->get('site_name'));