<?php
/**
 * config/database.php — লাইভ সার্ভার ভার্সন
 *
 * ১. এই ফাইলটা database.php নামে save করুন
 * ২. uploads/ ফোল্ডারে 755 permission দিন
 * ৩. database.sql import করুন
 */

if (ob_get_level() === 0) ob_start();

// ════════════════════════════════════════════
//  🔧 এখানে আপনার তথ্য দিন
// ════════════════════════════════════════════
define('DB_HOST',    'localhost');
define('DB_NAME',    'atxaizuv_style_eden');          // ← লাইভ DB নাম
define('DB_USER',    'atxaizuv_Jahangirweb2');         // ← লাইভ DB user
define('DB_PASS',    'PlPlPl90@#');                    // ← লাইভ DB password
define('DB_CHARSET', 'utf8mb4');

define('BASE_URL',   'http://demo6.dotnests.site');    // ← লাইভ URL (trailing slash ছাড়া)
// ════════════════════════════════════════════

// Upload paths — স্বয়ংক্রিয়ভাবে সেট হয়
$_rootPath    = dirname(__DIR__);
$_uploadsPath = $_rootPath . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR;
if (!is_dir($_uploadsPath)) @mkdir($_uploadsPath, 0755, true);

define('UPLOADS_PATH', $_uploadsPath);
define('UPLOADS_URL',  BASE_URL . '/uploads/');

try {
    $pdo = new PDO(
        "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET,
        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) {
    ob_end_clean();
    die('<div style="font-family:sans-serif;padding:24px;color:#c53030;">DB Error: ' . htmlspecialchars($e->getMessage()) . '</div>');
}

if (session_status() === PHP_SESSION_NONE) session_start();

function e($str) { return htmlspecialchars((string)($str ?? ''), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }

function redirect($url) {
    while (ob_get_level() > 0) ob_end_clean();
    header('Location: ' . $url, true, 302);
    exit;
}

function getSetting($pdo, $key) {
    $s = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key=?");
    $s->execute([$key]); $r = $s->fetch();
    return $r ? $r['setting_value'] : null;
}

function getAllSettings($pdo) {
    $out = [];
    foreach ($pdo->query("SELECT setting_key,setting_value FROM settings")->fetchAll() as $r)
        $out[$r['setting_key']] = $r['setting_value'];
    return $out;
}

function uploadImage($file, $folder = 'products') {
    if (!isset($file['error']) || $file['error'] !== UPLOAD_ERR_OK) return false;
    $allowedMimes = ['image/jpeg','image/png','image/gif','image/webp'];
    $extMap       = ['image/jpeg'=>'jpg','image/png'=>'png','image/gif'=>'gif','image/webp'=>'webp'];
    if (function_exists('finfo_open')) {
        $mime = (new finfo(FILEINFO_MIME_TYPE))->file($file['tmp_name']);
    } else {
        $e2 = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $mime = match($e2){'jpg','jpeg'=>'image/jpeg','png'=>'image/png','gif'=>'image/gif','webp'=>'image/webp',default=>'unknown'};
    }
    if (!in_array($mime, $allowedMimes)) return false;
    if ($file['size'] > 8*1024*1024 || $file['size']===0) return false;
    $filename = 'img_' . uniqid() . '_' . time() . '.' . ($extMap[$mime]??'jpg');
    $dir = UPLOADS_PATH . $folder . DIRECTORY_SEPARATOR;
    if (!is_dir($dir)) { if (!mkdir($dir,0755,true)) return false; }
    if (!is_writable($dir)) { @chmod($dir,0755); if (!is_writable($dir)) return false; }
    if (!move_uploaded_file($file['tmp_name'], $dir.$filename)) return false;
    return $folder . '/' . $filename;
}

function uploadError($file) {
    if (!isset($file['error'])) return 'ফাইল নেই';
    $c=[0=>'OK',1=>'INI size',2=>'Form size',3=>'Partial',4=>'No file',6=>'No tmp',7=>'Write fail',8=>'Extension'];
    return ($c[$file['error']]??'Unknown:'.$file['error']).' | Path:'.UPLOADS_PATH.' | Write:'.(is_writable(UPLOADS_PATH)?'Yes':'No');
}

function makeSlug($t) {
    $s=trim(mb_strtolower(preg_replace('/[^\p{L}\p{N}]+/u','-',$t),'UTF-8'),'-');
    return $s?:'item-'.uniqid();
}

function isLoggedIn() { return !empty($_SESSION['user_id']); }
function isAdmin()    { return isset($_SESSION['role']) && $_SESSION['role']==='admin'; }
function isInvestor() { return isset($_SESSION['role']) && $_SESSION['role']==='investor'; }
function requireAdmin()    { if(!isAdmin())    redirect(BASE_URL.'/admin/login.php'); }
function requireLogin()    { if(!isLoggedIn()) redirect(BASE_URL.'/login.php'); }
function requireInvestor() { if(!isInvestor()&&!isAdmin()) redirect(BASE_URL.'/login.php'); }
