<?php
session_start();
error_reporting(E_ALL);
// Force errors to display on screen to prevent generic 500 errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

// Global Paths
$config_file = __DIR__ . '/dle_config.json';
$uploads_dir = __DIR__ . '/uploads';
$htaccess_file = __DIR__ . '/.htaccess';

// Ensure uploads directory exists and is writable
if (!is_dir($uploads_dir)) {
    @mkdir($uploads_dir, 0755, true);
}

$route = $_GET['route'] ?? '';
$action = $_GET['action'] ?? '';
$slug = '';

if (!empty($route)) {
    $parts = explode('/', trim($route, '/'));
    if ($parts[0] === 'post' && isset($parts[1])) {
        $action = 'read_post';
        $slug = $parts[1];
    } elseif ($parts[0] === 'category' && isset($parts[1])) {
        $action = 'category';
        $slug = $parts[1];
    } elseif ($parts[0] === 'rules') {
        $action = 'rules';
    }
}

$error = '';
$success = '';
$pdo = null;
$is_installed = file_exists($config_file);

if ($is_installed) {
    $cfg = json_decode(file_get_contents($config_file), true);
    if ($cfg) {
        try {
            $pdo = new PDO("mysql:host={$cfg['db_host']};dbname={$cfg['db_name']};charset=utf8mb4", $cfg['db_user'], $cfg['db_pass']);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

            // AUTO-PATCHER: Prevents 500 Errors by silently injecting missing columns individually
            $user_cols = [
                'email' => 'VARCHAR(255) NULL',
                'is_active' => 'TINYINT(1) DEFAULT 1',
                'reset_token' => 'VARCHAR(100) NULL',
                'avatar_path' => 'VARCHAR(255) NULL'
            ];
            foreach ($user_cols as $col => $def) {
                try {
                    $pdo->query("SELECT `$col` FROM dle_users LIMIT 1");
                } catch (PDOException $e) {
                    $pdo->exec("ALTER TABLE dle_users ADD COLUMN `$col` $def");
                }
            }
            
            try {
                $pdo->exec("INSERT IGNORE INTO dle_settings (key_name, value) VALUES ('mail_enabled', '0'), ('mail_from', 'noreply@site.com')");
            } catch (PDOException $e) {}
            
            try {
                $pdo->query("SELECT featured_image FROM dle_posts LIMIT 1");
            } catch (PDOException $patchError) {
                $pdo->exec("ALTER TABLE dle_posts ADD COLUMN featured_image VARCHAR(255) NULL");
            }

        } catch (PDOException $e) {
            die("<div style='font-family:sans-serif; padding:40px; background:#f4f4f4; text-align:center;'>
                <h2 style='color:#d32f2f;'>Database Connection Error</h2>
                <p>The system could not connect to the database. Please check your credentials or delete <b>dle_config.json</b> to reinstall.</p>
                <code style='display:inline-block; margin-top:20px; padding:10px; background:#fff; border:1px solid #ddd;'>" . htmlspecialchars($e->getMessage()) . "</code>
                </div>");
        }
    }
} elseif ($action !== 'install') {
    header("Location: ?action=install");
    exit;
}

function slugify($text) {
    $text = preg_replace('~[^\pL\d]+~u', '-', $text);
    $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
    $text = preg_replace('~[^-\w]+~', '', $text);
    $text = trim($text, '-');
    $text = preg_replace('~-+~', '-', $text);
    return strtolower($text);
}

function handle_upload($input_name, $allowed_types = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'ico']) {
    global $uploads_dir;
    if (isset($_FILES[$input_name]) && $_FILES[$input_name]['error'] === UPLOAD_ERR_OK) {
        $ext = strtolower(pathinfo($_FILES[$input_name]['name'], PATHINFO_EXTENSION));
        if (in_array($ext, $allowed_types)) {
            $filename = uniqid() . '_' . time() . '.' . $ext;
            $target = $uploads_dir . '/' . $filename;
            if (move_uploaded_file($_FILES[$input_name]['tmp_name'], $target)) {
                return 'uploads/' . $filename;
            }
        }
    }
    return false;
}

function send_dle_mail($to, $subject, $message) {
    global $settings;
    if (empty($settings['mail_enabled']) || $settings['mail_enabled'] === '0') return true;
    
    $from = !empty($settings['mail_from']) ? $settings['mail_from'] : 'noreply@' . $_SERVER['HTTP_HOST'];
    $headers  = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=utf-8\r\n";
    $headers .= "From: {$settings['site_title']} <{$from}>\r\n";
    
    return @mail($to, $subject, $message, $headers);
}

$settings = [
    'site_title' => 'DataLife Engine Clone',
    'seo_desc' => 'Soft & News Portal Powered by SQL',
    'seo_keys' => '',
    'logo_path' => '',
    'favicon_path' => '',
    'mail_enabled' => '0',
    'mail_from' => '',
    'site_rules' => '<p>Welcome to our site! Please follow the rules.</p>'
];
$categories = [];
$current_user = null;

if ($pdo) {
    try {
        $stmt = $pdo->query("SELECT * FROM dle_settings");
        while ($row = $stmt->fetch()) {
            $settings[$row['key_name']] = $row['value'];
        }
        $stmt = $pdo->query("SELECT * FROM dle_categories ORDER BY name ASC");
        $categories = $stmt->fetchAll();
        
        if (isset($_SESSION['user_id'])) {
            $stmt = $pdo->prepare("SELECT * FROM dle_users WHERE id = ?");
            $stmt->execute([$_SESSION['user_id']]);
            $current_user = $stmt->fetch();
        }
    } catch (PDOException $e) {
        die("Settings Load Error: " . htmlspecialchars($e->getMessage()));
    }
}

if ($action === 'install' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $db_host = $_POST['db_host'] ?? 'localhost';
    $db_name = $_POST['db_name'] ?? '';
    $db_user = $_POST['db_user'] ?? '';
    $db_pass = $_POST['db_pass'] ?? '';
    $admin_user = $_POST['admin_user'] ?? 'admin';
    $admin_pass = $_POST['admin_pass'] ?? 'password';
    $admin_email = $_POST['admin_email'] ?? 'admin@site.com';

    try {
        $temp_pdo = new PDO("mysql:host=$db_host;charset=utf8mb4", $db_user, $db_pass);
        $temp_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        $temp_pdo->exec("CREATE DATABASE IF NOT EXISTS `$db_name`");
        $temp_pdo->exec("USE `$db_name`");

        // Schema Generation
        $temp_pdo->exec("CREATE TABLE IF NOT EXISTS dle_settings (key_name VARCHAR(100) PRIMARY KEY, value TEXT)");
        $temp_pdo->exec("CREATE TABLE IF NOT EXISTS dle_users (id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50), email VARCHAR(255), password VARCHAR(255), role VARCHAR(20), is_active TINYINT(1) DEFAULT 1, reset_token VARCHAR(100), avatar_path VARCHAR(255))");
        $temp_pdo->exec("CREATE TABLE IF NOT EXISTS dle_categories (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), slug VARCHAR(100))");
        $temp_pdo->exec("CREATE TABLE IF NOT EXISTS dle_posts (id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255), slug VARCHAR(255), content TEXT, category_id INT, author_id INT, featured_image VARCHAR(255), created_at DATETIME)");

        // Initial Data
        $temp_pdo->exec("INSERT IGNORE INTO dle_settings (key_name, value) VALUES ('site_title', 'My DLE Portal'), ('seo_desc', 'Soft & News Portal Powered by SQL'), ('seo_keys', 'news, soft'), ('mail_enabled', '0')");
        $temp_pdo->exec("INSERT IGNORE INTO dle_categories (name, slug) VALUES ('Software', 'software'), ('News', 'news')");
        
        $hash = password_hash($admin_pass, PASSWORD_DEFAULT);
        $temp_pdo->prepare("INSERT INTO dle_users (username, email, password, role, is_active) VALUES (?, ?, ?, 'admin', 1)")->execute([$admin_user, $admin_email, $hash]);

        // Generate .htaccess for SEO URLs
        $base_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $base_dir = rtrim(dirname($base_path), '/\\');
        $base_dir = ($base_dir === '') ? '/' : $base_dir . '/';
        
        $ht_content = "RewriteEngine On\nRewriteBase {$base_dir}\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule ^(.*)$ index.php?route=$1 [QSA,L]\n";
        file_put_contents($htaccess_file, $ht_content);

        // Save Config
        file_put_contents($config_file, json_encode(['db_host' => $db_host, 'db_name' => $db_name, 'db_user' => $db_user, 'db_pass' => $db_pass]));
        
        header("Location: /");
        exit;
    } catch (PDOException $e) {
        $error = "SQL Installation Error: " . $e->getMessage();
    }
}

if ($action === 'login' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['login_user'] ?? '';
    $password = $_POST['login_pass'] ?? '';

    $stmt = $pdo->prepare("SELECT * FROM dle_users WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password'])) {
        if ($user['is_active'] == 0) {
            $error = "Your account is not activated. Please check your email.";
        } else {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = $user['role'];
            header("Location: /");
            exit;
        }
    } else {
        $error = "Invalid username or password.";
    }
}

if ($action === 'logout') {
    session_destroy();
    header("Location: /");
    exit;
}

if ($action === 'upload_avatar' && isset($_SESSION['user_id']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $avatar = handle_upload('avatar_file');
    if ($avatar) {
        $stmt = $pdo->prepare("UPDATE dle_users SET avatar_path = ? WHERE id = ?");
        $stmt->execute([$avatar, $_SESSION['user_id']]);
        $success = "Avatar successfully updated!";
        // Refresh active user state
        $current_user['avatar_path'] = $avatar; 
    } else {
        $error = "Failed to upload avatar. Allowed formats: JPG, PNG, GIF, WEBP.";
    }
    $action = ''; // return home
}

if ($action === 'register' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $user = trim($_POST['reg_user'] ?? '');
    $email = trim($_POST['reg_email'] ?? '');
    $pass = $_POST['reg_pass'] ?? '';

    if (!empty($user) && !empty($email) && !empty($pass)) {
        $stmt = $pdo->prepare("SELECT id FROM dle_users WHERE username = ? OR email = ?");
        $stmt->execute([$user, $email]);
        if ($stmt->fetch()) {
            $error = "Username or email already exists.";
        } else {
            $hash = password_hash($pass, PASSWORD_DEFAULT);
            $token = bin2hex(random_bytes(16));
            $is_active = ($settings['mail_enabled'] === '1') ? 0 : 1;
            
            $stmt = $pdo->prepare("INSERT INTO dle_users (username, email, password, role, is_active, reset_token) VALUES (?, ?, ?, 'user', ?, ?)");
            $stmt->execute([$user, $email, $hash, $is_active, $token]);

            if ($is_active === 0) {
                $link = "http://" . $_SERVER['HTTP_HOST'] . "/?action=activate&token=" . $token;
                $msg = "Hello $user,<br><br>Please click the link below to activate your account:<br><a href='$link'>$link</a>";
                send_dle_mail($email, "Account Activation", $msg);
                $success = "Registration successful! Please check your email to activate your account.";
            } else {
                $success = "Registration successful! You may now log in.";
            }
            $action = ''; 
        }
    }
}

if ($action === 'activate' && isset($_GET['token'])) {
    $stmt = $pdo->prepare("UPDATE dle_users SET is_active = 1, reset_token = NULL WHERE reset_token = ?");
    $stmt->execute([$_GET['token']]);
    if ($stmt->rowCount() > 0) {
        $success = "Account activated successfully! You can now log in.";
    } else {
        $error = "Invalid or expired activation link.";
    }
    $action = '';
}

if ($action === 'reset_pass' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['reset_email'] ?? '');
    $stmt = $pdo->prepare("SELECT * FROM dle_users WHERE email = ?");
    $stmt->execute([$email]);
    if ($user = $stmt->fetch()) {
        $token = bin2hex(random_bytes(16));
        $pdo->prepare("UPDATE dle_users SET reset_token = ? WHERE id = ?")->execute([$token, $user['id']]);
        
        $link = "http://" . $_SERVER['HTTP_HOST'] . "/?action=new_pass&token=" . $token;
        $msg = "Click here to reset your password: <a href='$link'>$link</a>";
        send_dle_mail($email, "Password Reset", $msg);
        $success = "If your email exists in our system, a password reset link has been sent.";
    }
    $action = '';
}

if ($action === 'new_pass_save' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['token'] ?? '';
    $pass = $_POST['new_pass'] ?? '';
    $hash = password_hash($pass, PASSWORD_DEFAULT);
    
    $stmt = $pdo->prepare("UPDATE dle_users SET password = ?, reset_token = NULL WHERE reset_token = ?");
    $stmt->execute([$hash, $token]);
    if ($stmt->rowCount() > 0) {
        $success = "Password updated! You can now log in.";
    } else {
        $error = "Invalid token.";
    }
    $action = '';
}

$is_admin = isset($_SESSION['role']) && $_SESSION['role'] === 'admin';

if ($action === 'admin_save_settings' && $is_admin && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $updates = [
        'site_title' => $_POST['site_title'] ?? '',
        'seo_desc' => $_POST['seo_desc'] ?? '',
        'seo_keys' => $_POST['seo_keys'] ?? '',
        'mail_enabled' => isset($_POST['mail_enabled']) ? '1' : '0',
        'mail_from' => $_POST['mail_from'] ?? '',
        'site_rules' => $_POST['site_rules'] ?? ''
    ];

    $logo = handle_upload('logo_upload');
    if ($logo) $updates['logo_path'] = $logo;

    $favicon = handle_upload('favicon_upload');
    if ($favicon) $updates['favicon_path'] = $favicon;

    $stmt = $pdo->prepare("REPLACE INTO dle_settings (key_name, value) VALUES (?, ?)");
    foreach ($updates as $key => $val) {
        $stmt->execute([$key, $val]);
    }
    header("Location: ?action=admin&success=Settings updated");
    exit;
}

if ($action === 'admin_add_category' && $is_admin && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $cat_name = trim($_POST['cat_name']);
    if (!empty($cat_name)) {
        $stmt = $pdo->prepare("INSERT INTO dle_categories (name, slug) VALUES (?, ?)");
        $stmt->execute([$cat_name, slugify($cat_name)]);
        header("Location: ?action=admin&success=Category Added");
        exit;
    }
}

if ($action === 'admin_edit_category_exec' && $is_admin && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $stmt = $pdo->prepare("UPDATE dle_categories SET name = ?, slug = ? WHERE id = ?");
    $stmt->execute([trim($_POST['cat_name']), slugify($_POST['cat_name']), $_POST['cat_id']]);
    header("Location: ?action=admin&success=Category Updated");
    exit;
}

if ($action === 'delete_category_execute' && $is_admin && isset($_POST['confirm_delete_cat'])) {
    $stmt = $pdo->prepare("DELETE FROM dle_categories WHERE id = ?");
    $stmt->execute([$_POST['cat_id']]);
    header("Location: ?action=admin&success=Category Deleted");
    exit;
}

if ($action === 'admin_update_core' && $is_admin && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_FILES['core_file']) && $_FILES['core_file']['error'] === UPLOAD_ERR_OK) {
        $ext = strtolower(pathinfo($_FILES['core_file']['name'], PATHINFO_EXTENSION));
        if ($ext === 'php') {
            if (move_uploaded_file($_FILES['core_file']['tmp_name'], __FILE__)) {
                header("Location: ?action=admin&success=System Core Patched Successfully");
                exit;
            } else {
                $error = "Failed to overwrite core file. Check permissions.";
            }
        } else {
            $error = "Only .php files allowed for core update.";
        }
    }
    $action = 'admin';
}

if ($action === 'add_post' && $is_admin && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['post_title'] ?? '';
    $cat_id = $_POST['category_id'] ?? 1;
    $content = $_POST['post_content'] ?? '';
    $featured_image = handle_upload('featured_image');
    
    if (!empty($title) && !empty($content)) {
        $stmt = $pdo->prepare("INSERT INTO dle_posts (title, slug, content, category_id, author_id, featured_image, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())");
        $stmt->execute([$title, slugify($title), $content, $cat_id, $_SESSION['user_id'], $featured_image]);
        header("Location: /");
        exit;
    }
}

if ($action === 'delete_post_execute' && $is_admin && isset($_POST['confirm_delete'])) {
    $stmt = $pdo->prepare("DELETE FROM dle_posts WHERE id = ?");
    $stmt->execute([$_POST['post_id']]);
    header("Location: /");
    exit;
}

if ($action === 'edit_post_execute' && $is_admin && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $post_id = $_POST['post_id'] ?? 0;
    $title = $_POST['post_title'] ?? '';
    $cat_id = $_POST['category_id'] ?? 1;
    $content = $_POST['post_content'] ?? '';
    $featured_image = handle_upload('featured_image');
    
    if (!empty($title) && !empty($content) && $post_id) {
        if ($featured_image) {
            $stmt = $pdo->prepare("UPDATE dle_posts SET title = ?, slug = ?, content = ?, category_id = ?, featured_image = ? WHERE id = ?");
            $stmt->execute([$title, slugify($title), $content, $cat_id, $featured_image, $post_id]);
        } else {
            $stmt = $pdo->prepare("UPDATE dle_posts SET title = ?, slug = ?, content = ?, category_id = ? WHERE id = ?");
            $stmt->execute([$title, slugify($title), $content, $cat_id, $post_id]);
        }
        header("Location: /post/" . slugify($title));
        exit;
    }
}

$posts = [];
$single_post = null;

if ($pdo) {
    if ($action === 'read_post' && !empty($slug)) {
        $stmt = $pdo->prepare("SELECT p.*, c.name as category_name, u.username as author_name FROM dle_posts p LEFT JOIN dle_categories c ON p.category_id = c.id LEFT JOIN dle_users u ON p.author_id = u.id WHERE p.slug = ?");
        $stmt->execute([$slug]);
        $single_post = $stmt->fetch();
    } elseif ($action === 'category' && !empty($slug)) {
        $stmt = $pdo->prepare("SELECT p.*, c.name as category_name, u.username as author_name FROM dle_posts p JOIN dle_categories c ON p.category_id = c.id LEFT JOIN dle_users u ON p.author_id = u.id WHERE c.slug = ? ORDER BY p.created_at DESC");
        $stmt->execute([$slug]);
        $posts = $stmt->fetchAll();
    } else {
        $stmt = $pdo->query("SELECT p.*, c.name as category_name, u.username as author_name FROM dle_posts p LEFT JOIN dle_categories c ON p.category_id = c.id LEFT JOIN dle_users u ON p.author_id = u.id ORDER BY p.created_at DESC");
        $posts = $stmt->fetchAll();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><?= htmlspecialchars($settings['site_title']) ?></title>
    <meta name="description" content="<?= htmlspecialchars($settings['seo_desc']) ?>">
    <meta name="keywords" content="<?= htmlspecialchars($settings['seo_keys']) ?>">
    <?php if (!empty($settings['favicon_path'])): ?>
        <link rel="icon" href="/<?= htmlspecialchars($settings['favicon_path']) ?>">
    <?php endif; ?>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/6.8.3/tinymce.min.js" referrerpolicy="origin"></script>
    <style>
        body { background-color: #e2e4e7; background-image: url('data:image/svg+xml;utf8,<svg width="4" height="4" xmlns="http://www.w3.org/2000/svg"><rect width="4" height="4" fill="%23e2e4e7"/><rect width="2" height="2" fill="%23d6d9de"/></svg>'); font-family: Tahoma, Arial, sans-serif; color: #404040; font-size: 13px; line-height: 1.5; }
        .dle-header { background: #1c5eb5; background: linear-gradient(to bottom, #2a73cc 0%, #1754a6 100%); color: white; padding: 25px 0; border-bottom: 5px solid #103c7a; box-shadow: 0 4px 10px rgba(0,0,0,0.15); }
        .dle-title { font-size: 34px; font-weight: normal; color: #fff; text-decoration: none; text-shadow: 1px 2px 2px rgba(0,0,0,0.4); font-family: "Trebuchet MS", Tahoma, sans-serif; display: flex; align-items: center; gap: 15px; }
        .dle-title img { max-height: 45px; filter: drop-shadow(0px 2px 3px rgba(0,0,0,0.3)); }
        .dle-block { background: #fff; border-radius: 3px; box-shadow: 0 1px 3px rgba(0,0,0,0.15); margin-bottom: 20px; border: 1px solid #c9d0d6; overflow: hidden; }
        .dle-block-title { background: #f0f4f8; background: linear-gradient(to bottom, #f9fafb, #e4eaf0); border-bottom: 1px solid #d0d7de; border-top: 2px solid #3676c8; padding: 12px 15px; font-weight: bold; color: #1c4b82; font-size: 14px; text-transform: uppercase; text-shadow: 1px 1px 0 #fff; display: flex; align-items: center; gap: 8px;}
        .dle-block-content { padding: 18px; }
        .dle-post-title { font-size: 22px; font-weight: normal; color: #1754a6; margin-bottom: 10px; font-family: "Trebuchet MS", Arial, sans-serif; }
        .dle-post-title a:hover { color: #cc3300; text-decoration: underline; }
        .dle-post-meta { font-size: 11px; color: #6b7a88; margin-bottom: 15px; display: flex; gap: 15px; border-bottom: 1px solid #e1e6ec; padding-bottom: 10px; background: #f7f9fa; padding: 10px; border-radius: 2px; box-shadow: inset 0 1px 2px rgba(0,0,0,0.02); }
        .dle-input { width: 100%; border: 1px solid #bbc4ce; padding: 8px 10px; border-radius: 3px; box-shadow: inset 0 2px 4px rgba(0,0,0,0.04); font-size: 13px; margin-bottom: 10px; outline: none; background: #fff; transition: all 0.2s; }
        .dle-input:focus { border-color: #3676c8; box-shadow: 0 0 5px rgba(54, 118, 200, 0.4); }
        .dle-btn { background: #2a73cc; background: linear-gradient(to bottom, #3b86e0, #1e63b8); color: white; border: 1px solid #144e99; padding: 9px 18px; border-radius: 3px; font-weight: bold; font-size: 12px; cursor: pointer; text-shadow: 0 -1px 0 rgba(0,0,0,0.3); box-shadow: inset 0 1px 0 rgba(255,255,255,0.3); text-transform: uppercase; }
        .dle-btn:hover { background: #3b86e0; background: linear-gradient(to bottom, #4994f0, #256bc2); }
        .dle-btn-red { background: linear-gradient(to bottom, #e85a5a, #c62d2d); border-color: #9e1a1a; }
        .dle-btn-red:hover { background: linear-gradient(to bottom, #f96b6b, #d83d3d); }
        
        .dle-html-content { font-size: 14px; line-height: 1.6; color: #2c3640; }
        .dle-html-content h1, .dle-html-content h2, .dle-html-content h3 { font-weight: normal; margin-top: 20px; margin-bottom: 12px; color: #1754a6; font-family: "Trebuchet MS", sans-serif; }
        .dle-html-content h1 { font-size: 1.8em; }
        .dle-html-content h2 { font-size: 1.5em; }
        .dle-html-content p { margin-bottom: 15px; }
        .dle-html-content ul { list-style-type: square; margin-left: 20px; margin-bottom: 15px; color: #555; }
        .dle-html-content ol { list-style-type: decimal; margin-left: 20px; margin-bottom: 15px; }
        .dle-html-content a { color: #1754a6; text-decoration: underline; }
        .dle-html-content a:hover { color: #cc3300; }
        .dle-html-content img { max-width: 100%; height: auto; margin-bottom: 15px; border-radius: 3px; border: 1px solid #ccc; padding: 2px; }
        .dle-html-content blockquote { border-left: 4px solid #3676c8; padding-left: 15px; color: #5a6b7c; font-style: italic; margin-bottom: 15px; background: #f0f4f8; padding: 12px 15px; border-radius: 0 3px 3px 0; }
    </style>
</head>
<body>
    <div class="dle-header">
        <div class="max-w-6xl mx-auto px-6 flex justify-between items-center">
            <div>
                <a href="/" class="dle-title">
                    <?php if (!empty($settings['logo_path'])): ?>
                        <img src="/<?= htmlspecialchars($settings['logo_path']) ?>" alt="Logo">
                    <?php endif; ?>
                    <?= htmlspecialchars($settings['site_title']); ?>
                </a>
                <div class="text-sm text-blue-200 mt-1">Soft & News Portal Powered by SQL</div>
            </div>
            <div class="text-sm font-medium bg-blue-800 bg-opacity-50 px-4 py-2 rounded">
                <?= !$is_installed ? 'Setup Mode' : (isset($_SESSION['username']) ? 'Welcome, ' . htmlspecialchars($_SESSION['username']) : 'Guest Mode'); ?>
            </div>
        </div>
    </div>

    <!-- NEW MAIN NAVIGATION MENU HEADER -->
    <div class="bg-[#103c7a] border-b border-[#0a2752] shadow-md relative z-10">
        <div class="max-w-6xl mx-auto px-6 flex flex-wrap items-center text-[13px] font-bold tracking-wide">
            <a href="/" class="px-5 py-3 text-white hover:bg-[#1c5eb5] transition-colors flex items-center gap-2 border-x border-[#1a4a8f]">
                🏠 Home Feed
            </a>
            <?php foreach(array_slice($categories, 0, 6) as $c): ?>
                <a href="/category/<?= htmlspecialchars($c['slug']) ?>" class="px-5 py-3 text-[#d1e4fb] hover:bg-[#1c5eb5] hover:text-white transition-colors border-r border-[#1a4a8f]">
                    <?= htmlspecialchars($c['name']) ?>
                </a>
            <?php endforeach; ?>
            <a href="/rules" class="px-5 py-3 text-[#d1e4fb] hover:bg-[#1c5eb5] hover:text-white transition-colors border-r border-[#1a4a8f]">
                📊 Site Rules
            </a>
            
            <div class="ml-auto flex">
                <?php if ($is_admin): ?>
                    <a href="?action=admin" class="px-5 py-3 bg-[#e85a5a] text-white hover:bg-[#d83d3d] transition-colors border-x border-[#c62d2d] shadow-inner">
                        ⚙️ Admin Control Panel
                    </a>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="max-w-6xl mx-auto px-6 py-8">
        <?php if (!empty($error)): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6 font-bold"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>
        <?php if (!empty($_GET['success']) || !empty($success)): ?>
            <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-6 font-bold"><?= htmlspecialchars($_GET['success'] ?? $success) ?></div>
        <?php endif; ?>

        <?php if ($action === 'install'): ?>
            <div class="max-w-xl mx-auto dle-block">
                <div class="dle-block-title !bg-blue-600 !text-white !text-shadow-none border-blue-800">🚀 SQL Database Auto-Installer</div>
                <div class="dle-block-content bg-gray-50">
                    <p class="text-sm text-gray-600 mb-6 pb-4 border-b border-gray-200">
                        Welcome! Please provide your MySQL database credentials. The system will auto-patch all tables.
                    </p>
                    <form method="POST">
                        <div class="grid grid-cols-2 gap-4 mb-2">
                            <div><label class="block text-xs font-bold text-gray-600 mb-1">MySQL Host</label><input type="text" name="db_host" value="localhost" class="dle-input"></div>
                            <div><label class="block text-xs font-bold text-gray-600 mb-1">Database Name</label><input type="text" name="db_name" required class="dle-input"></div>
                        </div>
                        <div class="grid grid-cols-2 gap-4 mb-4">
                            <div><label class="block text-xs font-bold text-gray-600 mb-1">DB Username</label><input type="text" name="db_user" required class="dle-input"></div>
                            <div><label class="block text-xs font-bold text-gray-600 mb-1">DB Password</label><input type="password" name="db_pass" class="dle-input"></div>
                        </div>
                        <hr class="my-4">
                        <div class="grid grid-cols-3 gap-4 mb-6">
                            <div><label class="block text-xs font-bold text-gray-600 mb-1">Admin Username</label><input type="text" name="admin_user" value="admin" class="dle-input"></div>
                            <div><label class="block text-xs font-bold text-gray-600 mb-1">Admin Email</label><input type="email" name="admin_email" required class="dle-input"></div>
                            <div><label class="block text-xs font-bold text-gray-600 mb-1">Admin Password</label><input type="password" name="admin_pass" required class="dle-input"></div>
                        </div>
                        <button type="submit" class="dle-btn w-full">Install System Core</button>
                    </form>
                </div>
            </div>

        <?php elseif ($action === 'admin' && $is_admin): ?>
            <!-- STYLED PREMIUM ADMIN PANEL OVERHAUL -->
            <div class="flex flex-col md:flex-row gap-0 min-h-[650px] bg-[#f8fafc] border border-[#cbd5e1] rounded-xl shadow-lg overflow-hidden">
                <!-- Premium Dark Sidebar -->
                <div class="w-full md:w-72 bg-gradient-to-b from-[#0f172a] to-[#1e293b] text-gray-300 flex-shrink-0 flex flex-col relative">
                    <div class="p-6 font-extrabold text-xl text-white border-b border-[#334155] bg-[#0f172a] flex items-center gap-3 shadow-md">
                        <span class="bg-blue-600 text-white p-1.5 rounded-lg shadow-inner">⚙️</span> Control Panel
                    </div>
                    <ul class="text-[14px] flex-1 mt-6 font-medium space-y-2 px-4">
                        <li>
                            <a href="/" class="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-[#334155] hover:text-white text-blue-400 transition-all border border-transparent hover:border-[#475569]">
                                <span>←</span> Back to Website
                            </a>
                        </li>
                        <li class="pt-4 pb-2 text-[10px] uppercase tracking-widest text-slate-500 font-bold">Configuration</li>
                        <li>
                            <a href="?action=admin" class="flex items-center gap-3 px-4 py-3 bg-blue-600 text-white rounded-lg shadow-md border border-blue-500">
                                <span>🛠️</span> System Settings
                            </a>
                        </li>
                        <li class="pt-4 pb-2 text-[10px] uppercase tracking-widest text-slate-500 font-bold">Content</li>
                        <li>
                            <a href="?action=add_post" class="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-[#334155] hover:text-white transition-all border border-transparent hover:border-[#475569]">
                                <span>📝</span> Publish Article
                            </a>
                        </li>
                    </ul>
                    <div class="p-5 text-[11px] text-center border-t border-[#334155] text-slate-500 uppercase tracking-widest font-bold bg-[#0f172a]">
                        CMS Engine Ultimate
                    </div>
                </div>

                <!-- Admin Main Workspace -->
                <div class="w-full p-8 space-y-8 bg-[#f1f5f9] overflow-y-auto">
                    
                    <!-- Dashboard Header -->
                    <div class="flex justify-between items-end border-b border-slate-300 pb-4">
                        <div>
                            <h2 class="text-3xl font-light text-slate-800 tracking-tight">Dashboard Overview</h2>
                            <p class="text-sm text-slate-500 font-medium mt-1">Manage your portal configuration and categories.</p>
                        </div>
                    </div>

                    <!-- Settings Card -->
                    <div class="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden transition-all hover:shadow-md">
                        <div class="bg-slate-50 border-b border-slate-200 px-6 py-4 flex items-center gap-3">
                            <span class="text-blue-600 text-xl drop-shadow-sm">🌐</span>
                            <h3 class="font-bold text-slate-700 text-base">Site, SEO & Mail Configuration</h3>
                        </div>
                        <div class="p-6">
                            <form method="POST" action="?action=admin_save_settings" enctype="multipart/form-data">
                                <label class="block text-xs font-bold mb-1.5 text-slate-600 uppercase tracking-wide">Site Title</label>
                                <input type="text" name="site_title" value="<?= htmlspecialchars($settings['site_title']) ?>" class="w-full border border-slate-300 rounded-lg px-4 py-2 bg-slate-50 focus:bg-white focus:border-blue-500 focus:ring-2 focus:ring-blue-100 outline-none transition-all mb-4 text-sm font-medium text-slate-800">
                                
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-4">
                                    <div>
                                        <label class="block text-xs font-bold mb-1.5 text-slate-600 uppercase tracking-wide">SEO Meta Description</label>
                                        <textarea name="seo_desc" class="w-full border border-slate-300 rounded-lg px-4 py-2 bg-slate-50 focus:bg-white focus:border-blue-500 focus:ring-2 focus:ring-blue-100 outline-none transition-all text-sm font-medium text-slate-800 h-24 resize-none"><?= htmlspecialchars($settings['seo_desc']) ?></textarea>
                                    </div>
                                    <div>
                                        <label class="block text-xs font-bold mb-1.5 text-slate-600 uppercase tracking-wide">SEO Meta Keywords</label>
                                        <input type="text" name="seo_keys" value="<?= htmlspecialchars($settings['seo_keys']) ?>" class="w-full border border-slate-300 rounded-lg px-4 py-2 bg-slate-50 focus:bg-white focus:border-blue-500 focus:ring-2 focus:ring-blue-100 outline-none transition-all text-sm font-medium text-slate-800 mb-6">
                                        
                                        <label class="block text-xs font-bold mb-1.5 text-slate-600 uppercase tracking-wide">Upload Site Logo</label>
                                        <input type="file" name="logo_upload" accept="image/*" class="text-sm w-full bg-white border border-slate-300 px-3 py-2 rounded-lg cursor-pointer file:mr-4 file:py-1 file:px-3 file:rounded file:border-0 file:text-xs file:font-bold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100 transition-all">
                                        <?php if(!empty($settings['logo_path'])) echo "<div class='text-[11px] mt-1.5 text-green-600 font-bold'>✓ Active logo installed</div>"; ?>
                                    </div>
                                </div>
                                
                                <div class="bg-indigo-50 border border-indigo-100 rounded-lg p-5 mb-6">
                                    <h4 class="font-bold text-indigo-900 mb-3 text-sm flex items-center gap-2"><span class="text-lg">📧</span> Mail & Registration Engine</h4>
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 items-center">
                                        <label class="flex items-center gap-3 text-sm cursor-pointer bg-white px-4 py-3 rounded-lg border border-indigo-100 shadow-sm">
                                            <input type="checkbox" name="mail_enabled" <?= (isset($settings['mail_enabled']) && $settings['mail_enabled'] === '1') ? 'checked' : '' ?> class="w-5 h-5 text-indigo-600 rounded focus:ring-indigo-500">
                                            <span class="text-slate-700 font-medium">Enable Email Activations & Resets</span>
                                        </label>
                                        <div>
                                            <label class="block text-xs font-bold mb-1 text-indigo-800 uppercase">System 'From' Address</label>
                                            <input type="email" name="mail_from" value="<?= htmlspecialchars($settings['mail_from'] ?? '') ?>" class="w-full border border-indigo-200 rounded-lg px-4 py-2 outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-100 text-sm font-medium" placeholder="noreply@yoursite.com">
                                        </div>
                                    </div>
                                </div>

                                <div class="mt-4 mb-6 pt-5 border-t border-slate-200">
                                    <label class="block text-xs font-bold mb-2 text-slate-600 uppercase tracking-wide flex items-center gap-2"><span>📜</span> Site Rules Content</label>
                                    <textarea id="rules_editor" name="site_rules" class="w-full border border-slate-300 rounded-lg outline-none text-sm text-slate-800"><?= htmlspecialchars($settings['site_rules'] ?? '') ?></textarea>
                                </div>

                                <div class="flex items-center justify-between border-t border-slate-200 pt-5">
                                    <div class="w-1/2 md:w-1/3">
                                        <label class="block text-xs font-bold mb-1.5 text-slate-600 uppercase tracking-wide">Favicon (.ico/.png)</label>
                                        <input type="file" name="favicon_upload" accept=".ico,.png" class="text-xs w-full bg-white border border-slate-300 p-1.5 rounded-lg cursor-pointer">
                                        <?php if(!empty($settings['favicon_path'])) echo "<div class='text-[11px] mt-1 text-green-600 font-bold'>✓ Favicon active</div>"; ?>
                                    </div>
                                    <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2.5 px-8 rounded-lg shadow-md transition-all hover:shadow-lg transform hover:-translate-y-0.5 border border-blue-700">
                                        💾 Save Configuration
                                    </button>
                                </div>
                            </form>
                            <script>
                                tinymce.init({
                                    selector: '#rules_editor',
                                    plugins: 'advlist autolink lists link image charmap preview anchor searchreplace visualblocks code fullscreen insertdatetime media table',
                                    toolbar: 'undo redo | bold italic | alignleft aligncenter alignright | bullist numlist outdent indent | link image | code',
                                    height: 300,
                                    menubar: false,
                                    promotion: false, branding: false
                                });
                            </script>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                        <!-- Category Manager Card -->
                        <div class="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden flex flex-col transition-all hover:shadow-md">
                            <div class="bg-slate-50 border-b border-slate-200 px-6 py-4 flex items-center gap-3">
                                <span class="text-blue-600 text-xl drop-shadow-sm">📁</span>
                                <h3 class="font-bold text-slate-700 text-base">Category Manager</h3>
                            </div>
                            <div class="p-6 flex-1 flex flex-col">
                                <ul class="text-sm space-y-3 mb-6 flex-1 overflow-y-auto max-h-48 pr-2">
                                    <?php foreach($categories as $c): ?>
                                        <li class="flex justify-between items-center bg-white p-3 border border-slate-200 rounded-lg shadow-sm hover:border-blue-300 transition-colors">
                                            <div>
                                                <span class="font-bold text-slate-800 text-sm"><?= htmlspecialchars($c['name']) ?></span>
                                                <span class="block text-[10px] text-slate-400 font-mono">/category/<?= htmlspecialchars($c['slug']) ?></span>
                                            </div>
                                            <div class="flex gap-2">
                                                <a href="?action=admin&edit_cat=<?= $c['id'] ?>" class="text-[11px] bg-blue-50 border border-blue-200 text-blue-700 px-3 py-1.5 rounded-md hover:bg-blue-100 font-bold transition-colors">Edit</a>
                                                <a href="?action=delete_category_prompt&id=<?= $c['id'] ?>" class="text-[11px] bg-red-50 border border-red-200 text-red-700 px-3 py-1.5 rounded-md hover:bg-red-100 font-bold transition-colors">Delete</a>
                                            </div>
                                        </li>
                                    <?php endforeach; ?>
                                </ul>
                                
                                <div class="bg-slate-50 p-5 rounded-lg border border-slate-200 shadow-inner mt-auto">
                                    <?php 
                                    $edit_cat = null;
                                    if (isset($_GET['edit_cat'])) {
                                        $stmt = $pdo->prepare("SELECT * FROM dle_categories WHERE id = ?");
                                        $stmt->execute([$_GET['edit_cat']]);
                                        $edit_cat = $stmt->fetch();
                                    }
                                    if ($edit_cat): ?>
                                        <form method="POST" action="?action=admin_edit_category_exec">
                                            <input type="hidden" name="cat_id" value="<?= $edit_cat['id'] ?>">
                                            <label class="block text-xs font-bold mb-2 text-slate-700 uppercase tracking-wide">✎ Edit Category</label>
                                            <input type="text" name="cat_name" value="<?= htmlspecialchars($edit_cat['name']) ?>" required class="w-full border border-slate-300 rounded-lg px-4 py-2 mb-3 focus:ring-2 focus:ring-blue-100 focus:border-blue-500 outline-none text-sm font-medium">
                                            <div class="flex gap-2">
                                                <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-5 text-xs rounded-lg shadow transition-colors">Save</button>
                                                <a href="?action=admin" class="bg-slate-500 hover:bg-slate-600 text-white font-bold py-2 px-5 text-xs rounded-lg shadow transition-colors flex items-center">Cancel</a>
                                            </div>
                                        </form>
                                    <?php else: ?>
                                        <form method="POST" action="?action=admin_add_category">
                                            <label class="block text-xs font-bold mb-2 text-slate-700 uppercase tracking-wide">➕ New Category</label>
                                            <div class="flex gap-2">
                                                <input type="text" name="cat_name" required class="flex-1 border border-slate-300 rounded-lg px-4 py-2 focus:ring-2 focus:ring-blue-100 focus:border-blue-500 outline-none text-sm font-medium" placeholder="Category Name...">
                                                <button type="submit" class="bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-2 px-5 text-xs rounded-lg shadow transition-colors whitespace-nowrap">Add</button>
                                            </div>
                                        </form>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <!-- System Updater Card -->
                        <div class="bg-white rounded-xl shadow-sm border border-rose-200 overflow-hidden flex flex-col transition-all hover:shadow-md">
                            <div class="bg-rose-50 border-b border-rose-200 px-6 py-4 flex items-center gap-3">
                                <span class="text-rose-600 text-xl drop-shadow-sm">⚠️</span>
                                <h3 class="font-bold text-rose-800 text-base">System Update & Patcher</h3>
                            </div>
                            <div class="p-6 flex-1 flex flex-col justify-center bg-gradient-to-b from-white to-rose-50/30">
                                <p class="text-sm text-slate-600 mb-5 leading-relaxed text-center">
                                    Upload a new <code class="bg-rose-100 text-rose-800 px-1.5 py-0.5 rounded text-xs font-bold">.php</code> core script to instantly upgrade the CMS without using FTP. This will overwrite the current index.php file safely.
                                </p>
                                <form method="POST" action="?action=admin_update_core" enctype="multipart/form-data" class="bg-white border border-rose-200 p-5 rounded-xl shadow-sm">
                                    <input type="file" name="core_file" accept=".php" required class="block w-full text-sm text-slate-500 file:mr-4 file:py-2.5 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-bold file:bg-rose-50 file:text-rose-700 hover:file:bg-rose-100 mb-4 border border-slate-200 rounded-lg cursor-pointer transition-all">
                                    <button type="submit" class="w-full bg-rose-600 hover:bg-rose-700 text-white font-bold py-3 rounded-lg shadow-md transition-all hover:shadow-lg border border-rose-800 flex items-center justify-center gap-2">
                                        <span>⚡</span> Install Core Update
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>

                </div>
            </div>

        <?php elseif ($action === 'delete_post_prompt' && $is_admin): ?>
            <div class="max-w-md mx-auto dle-block text-center py-8">
                <h2 class="text-xl font-bold text-red-600 mb-2">Delete Confirmation</h2>
                <form method="POST" action="?action=delete_post_execute" class="flex justify-center gap-4 mt-6">
                    <input type="hidden" name="post_id" value="<?= htmlspecialchars($_GET['id']) ?>">
                    <button type="submit" name="confirm_delete" class="dle-btn dle-btn-red">Yes, Delete</button>
                    <a href="/" class="dle-btn !bg-gray-500 !border-gray-600">Cancel</a>
                </form>
            </div>

        <?php elseif ($action === 'delete_category_prompt' && $is_admin): ?>
            <div class="max-w-md mx-auto dle-block text-center py-8">
                <h2 class="text-xl font-bold text-red-600 mb-2">Delete Category</h2>
                <form method="POST" action="?action=delete_category_execute" class="flex justify-center gap-4 mt-6">
                    <input type="hidden" name="cat_id" value="<?= htmlspecialchars($_GET['id']) ?>">
                    <button type="submit" name="confirm_delete_cat" class="dle-btn dle-btn-red">Yes, Delete</button>
                    <a href="?action=admin" class="dle-btn !bg-gray-500 !border-gray-600">Cancel</a>
                </form>
            </div>
            
        <?php elseif ($action === 'register'): ?>
            <div class="max-w-md mx-auto dle-block">
                <div class="dle-block-title">📝 User Registration</div>
                <div class="dle-block-content">
                    <form method="POST" action="?action=register">
                        <label class="block text-xs font-bold mb-1">Username</label>
                        <input type="text" name="reg_user" required class="dle-input">
                        <label class="block text-xs font-bold mb-1">Email</label>
                        <input type="email" name="reg_email" required class="dle-input">
                        <label class="block text-xs font-bold mb-1">Password</label>
                        <input type="password" name="reg_pass" required class="dle-input">
                        <button type="submit" class="dle-btn w-full mt-2">Register Account</button>
                        <a href="/" class="block text-center text-xs mt-3 text-blue-600 hover:underline">Cancel</a>
                    </form>
                </div>
            </div>
            
        <?php elseif ($action === 'forgot_pass'): ?>
            <div class="max-w-md mx-auto dle-block">
                <div class="dle-block-title">🔐 Reset Password</div>
                <div class="dle-block-content">
                    <form method="POST" action="?action=reset_pass">
                        <label class="block text-xs font-bold mb-1">Enter your Email</label>
                        <input type="email" name="reset_email" required class="dle-input">
                        <button type="submit" class="dle-btn w-full mt-2">Send Reset Link</button>
                        <a href="/" class="block text-center text-xs mt-3 text-blue-600 hover:underline">Cancel</a>
                    </form>
                </div>
            </div>
            
        <?php elseif ($action === 'new_pass'): ?>
            <div class="max-w-md mx-auto dle-block">
                <div class="dle-block-title">🔑 Enter New Password</div>
                <div class="dle-block-content">
                    <form method="POST" action="?action=new_pass_save">
                        <input type="hidden" name="token" value="<?= htmlspecialchars($_GET['token'] ?? '') ?>">
                        <label class="block text-xs font-bold mb-1">New Password</label>
                        <input type="password" name="new_pass" required class="dle-input">
                        <button type="submit" class="dle-btn w-full mt-2">Save Password</button>
                    </form>
                </div>
            </div>

        <?php else: ?>
            <div class="flex flex-col lg:flex-row gap-6">
                
                <!-- Main Feed Area -->
                <div class="flex-1">
                    <?php if ($action === 'rules'): ?>
                        <div class="dle-block">
                            <div class="dle-block-title">📊 Site Rules</div>
                            <div class="dle-block-content dle-html-content">
                                <?= !empty($settings['site_rules']) ? $settings['site_rules'] : '<p>No rules have been set yet.</p>' ?>
                            </div>
                        </div>

                    <?php elseif ($action === 'add_post'): ?>
                        <div class="dle-block">
                            <div class="dle-block-title">➕ Compose Article</div>
                            <div class="dle-block-content">
                                <form method="POST" action="?action=add_post" enctype="multipart/form-data">
                                    <label class="block text-xs font-bold mb-1">Title</label>
                                    <input type="text" name="post_title" required class="dle-input">
                                    
                                    <div class="grid grid-cols-2 gap-4 mb-2">
                                        <div>
                                            <label class="block text-xs font-bold mb-1">Category</label>
                                            <select name="category_id" class="dle-input bg-white">
                                                <?php foreach($categories as $c): ?>
                                                    <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['name']) ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div>
                                            <label class="block text-xs font-bold mb-1 text-blue-700">📸 Featured Image (Optional)</label>
                                            <input type="file" name="featured_image" accept="image/*" class="dle-input bg-white p-1.5 cursor-pointer">
                                        </div>
                                    </div>
                                    
                                    <label class="block text-xs font-bold mb-1 mt-2">Full Story</label>
                                    <textarea id="dle_wysiwyg" name="post_content" class="dle-input"></textarea>
                                    <button type="submit" class="dle-btn px-8 mt-4">Publish Now</button>
                                    <a href="/" class="dle-btn !bg-gray-500 !border-gray-600 ml-2">Cancel</a>
                                </form>
                                <script>
                                    tinymce.init({
                                        selector: '#dle_wysiwyg',
                                        plugins: 'advlist autolink lists link image charmap preview anchor searchreplace visualblocks code fullscreen insertdatetime media table',
                                        toolbar: 'undo redo | bold italic | alignleft aligncenter alignright | bullist numlist outdent indent | link image | code',
                                        height: 400,
                                        menubar: false,
                                        promotion: false, branding: false
                                    });
                                </script>
                            </div>
                        </div>

                    <?php elseif ($action === 'edit_post' && $is_admin && isset($_GET['id'])): ?>
                        <?php
                        $stmt = $pdo->prepare("SELECT * FROM dle_posts WHERE id = ?");
                        $stmt->execute([$_GET['id']]);
                        $edit_post = $stmt->fetch();
                        if ($edit_post):
                        ?>
                        <div class="dle-block">
                            <div class="dle-block-title">✏️ Edit Article</div>
                            <div class="dle-block-content">
                                <form method="POST" action="?action=edit_post_execute" enctype="multipart/form-data">
                                    <input type="hidden" name="post_id" value="<?= $edit_post['id'] ?>">
                                    <label class="block text-xs font-bold mb-1">Title</label>
                                    <input type="text" name="post_title" value="<?= htmlspecialchars($edit_post['title']) ?>" required class="dle-input">
                                    
                                    <div class="grid grid-cols-2 gap-4 mb-2">
                                        <div>
                                            <label class="block text-xs font-bold mb-1">Category</label>
                                            <select name="category_id" class="dle-input bg-white">
                                                <?php foreach($categories as $c): ?>
                                                    <option value="<?= $c['id'] ?>" <?= $c['id'] == $edit_post['category_id'] ? 'selected' : '' ?>><?= htmlspecialchars($c['name']) ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div>
                                            <label class="block text-xs font-bold mb-1 text-blue-700">📸 Replace Image (Leave blank to keep current)</label>
                                            <input type="file" name="featured_image" accept="image/*" class="dle-input bg-white p-1.5 cursor-pointer">
                                        </div>
                                    </div>
                                    
                                    <label class="block text-xs font-bold mb-1 mt-2">Full Story</label>
                                    <textarea id="dle_wysiwyg_edit" name="post_content" class="dle-input"><?= htmlspecialchars($edit_post['content']) ?></textarea>
                                    <button type="submit" class="dle-btn px-8 mt-4">Save Changes</button>
                                    <a href="/" class="dle-btn !bg-gray-500 !border-gray-600 ml-2">Cancel</a>
                                </form>
                                <script>
                                    tinymce.init({
                                        selector: '#dle_wysiwyg_edit',
                                        plugins: 'advlist autolink lists link image charmap preview anchor searchreplace visualblocks code fullscreen insertdatetime media table',
                                        toolbar: 'undo redo | bold italic | alignleft aligncenter alignright | bullist numlist outdent indent | link image | code',
                                        height: 400,
                                        menubar: false,
                                        promotion: false, branding: false
                                    });
                                </script>
                            </div>
                        </div>
                        <?php else: ?>
                            <div class="dle-block"><div class="dle-block-content text-center py-10">Article not found.</div></div>
                        <?php endif; ?>

                    <?php elseif ($action === 'read_post' && $single_post): ?>
                        <div class="dle-block">
                            <div class="dle-block-content">
                                <h1 class="text-3xl font-bold text-[#1b4f8d] mb-3"><?= htmlspecialchars($single_post['title']) ?></h1>
                                <div class="dle-post-meta">
                                    <span>Date: <?= htmlspecialchars($single_post['created_at']) ?></span>
                                    <span>Author: <b><?= htmlspecialchars($single_post['author_name']) ?></b></span>
                                    <span>Category: <b><?= htmlspecialchars($single_post['category_name']) ?></b></span>
                                </div>
                                <?php if (!empty($single_post['featured_image'])): ?>
                                    <img src="/<?= htmlspecialchars($single_post['featured_image']) ?>" class="w-full max-h-[400px] object-cover rounded mb-5 shadow-sm border border-gray-200">
                                <?php endif; ?>
                                <div class="dle-html-content">
                                    <?= $single_post['content'] ?>
                                </div>
                            </div>
                            <?php if ($is_admin): ?>
                                <div class="bg-gray-50 border-t px-4 py-3 flex justify-end gap-3">
                                    <a href="?action=edit_post&id=<?= $single_post['id'] ?>" class="text-xs bg-blue-100 text-blue-700 px-3 py-1 rounded border border-blue-300 hover:bg-blue-200">Edit Post</a>
                                    <a href="?action=delete_post_prompt&id=<?= $single_post['id'] ?>" class="text-xs bg-red-100 text-red-700 px-3 py-1 rounded border border-red-300 hover:bg-red-200">Delete Post</a>
                                </div>
                            <?php endif; ?>
                        </div>

                    <?php else: ?>
                        <?php foreach ($posts as $post): ?>
                            <div class="dle-block">
                                <div class="dle-block-title">
                                    <a href="/post/<?= htmlspecialchars($post['slug']) ?>" class="hover:underline"><?= htmlspecialchars($post['title']) ?></a>
                                </div>
                                <div class="dle-block-content">
                                    <div class="dle-post-meta !mb-3">
                                        <span>Date: <?= htmlspecialchars($post['created_at']) ?></span>
                                        <span>Author: <?= htmlspecialchars($post['author_name']) ?></span>
                                        <span>Category: <a href="/category/<?= slugify($post['category_name']) ?>" class="text-blue-600 hover:underline"><?= htmlspecialchars($post['category_name']) ?></a></span>
                                    </div>
                                    <?php if (!empty($post['featured_image'])): ?>
                                        <a href="/post/<?= htmlspecialchars($post['slug']) ?>">
                                            <img src="/<?= htmlspecialchars($post['featured_image']) ?>" class="w-full max-h-64 object-cover rounded mb-4 shadow-sm border border-gray-200 hover:opacity-90 transition">
                                        </a>
                                    <?php endif; ?>
                                    <div class="dle-html-content" style="max-height: 200px; overflow: hidden; position: relative;">
                                        <?= $post['content'] ?>
                                        <div style="position: absolute; bottom: 0; left: 0; right: 0; height: 60px; background: linear-gradient(transparent, #fff);"></div>
                                    </div>
                                    <div class="mt-4 border-t pt-3 flex justify-between items-center">
                                        <a href="/post/<?= htmlspecialchars($post['slug']) ?>" class="dle-btn !text-[11px] !py-1.5 !px-3">Full Story</a>
                                        <?php if ($is_admin): ?>
                                            <div class="flex gap-4">
                                                <a href="?action=edit_post&id=<?= $post['id'] ?>" class="text-xs text-blue-600 hover:underline font-bold">Edit</a>
                                                <a href="?action=delete_post_prompt&id=<?= $post['id'] ?>" class="text-xs text-red-600 hover:underline font-bold">Delete</a>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                        <?php if(empty($posts)): ?>
                            <div class="dle-block"><div class="dle-block-content text-center text-gray-500 py-10">No articles published yet.</div></div>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>

                <div class="w-full lg:w-72 space-y-5">
                    <div class="dle-block">
                        <div class="dle-block-title">🔒 User Panel</div>
                        <div class="dle-block-content !p-4">
                            <?php if (isset($_SESSION['user_id'])): ?>
                                <div class="flex items-center gap-3 mb-4 pb-4 border-b border-gray-200">
                                    <?php if (!empty($current_user['avatar_path'])): ?>
                                        <img src="/<?= htmlspecialchars($current_user['avatar_path']) ?>" class="w-12 h-12 rounded-full object-cover border-2 border-blue-300 shadow-sm">
                                    <?php else: ?>
                                        <div class="w-12 h-12 bg-blue-100 text-blue-600 text-xl font-bold rounded-full flex items-center justify-center border-2 border-blue-200">
                                            <?= strtoupper(substr($_SESSION['username'], 0, 1)) ?>
                                        </div>
                                    <?php endif; ?>
                                    <div class="leading-tight">
                                        <div class="font-bold text-sm text-gray-800"><?= htmlspecialchars($_SESSION['username']) ?></div>
                                        <div class="text-[11px] text-gray-500 capitalize"><?= htmlspecialchars($_SESSION['role']) ?></div>
                                    </div>
                                </div>
                                
                                <!-- Avatar Uploader Form -->
                                <form method="POST" action="?action=upload_avatar" enctype="multipart/form-data" class="mb-4 border-b border-gray-200 pb-4">
                                    <label class="block text-[10px] font-bold text-gray-500 uppercase tracking-wide mb-1">Update Avatar</label>
                                    <div class="flex gap-2 items-center">
                                        <input type="file" name="avatar_file" accept="image/*" class="text-[11px] w-full file:mr-2 file:py-1 file:px-2 file:border-0 file:text-[10px] file:bg-gray-100 file:text-gray-700 hover:file:bg-gray-200 file:rounded file:cursor-pointer bg-white border rounded p-1" required>
                                        <button type="submit" class="bg-blue-600 text-white text-[10px] px-3 py-1.5 rounded font-bold hover:bg-blue-700">Set</button>
                                    </div>
                                </form>

                                <div class="space-y-2 text-sm font-medium">
                                    <?php if ($is_admin): ?>
                                        <a href="?action=admin" class="block text-red-600 hover:underline bg-red-50 p-1.5 rounded text-center border border-red-200">⚙️ Admin Panel</a>
                                        <a href="?action=add_post" class="block text-blue-600 hover:underline bg-blue-50 p-1.5 rounded text-center border border-blue-200">📝 Add Article</a>
                                    <?php endif; ?>
                                    <a href="?action=logout" class="block text-gray-600 hover:underline text-center pt-2">🚪 Logout</a>
                                </div>
                            <?php else: ?>
                                <form method="POST" action="?action=login">
                                    <input type="text" name="login_user" placeholder="Username" class="dle-input !mb-2" required>
                                    <input type="password" name="login_pass" placeholder="Password" class="dle-input !mb-3" required>
                                    <button type="submit" class="dle-btn w-full">Log In</button>
                                </form>
                                <div class="flex justify-between mt-3 text-[11px]">
                                    <a href="?action=forgot_pass" class="text-gray-500 hover:text-blue-600 hover:underline">Forgot password?</a>
                                    <a href="?action=register" class="text-blue-600 font-bold hover:underline">Register</a>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="dle-block">
                        <div class="dle-block-title">📁 Categories</div>
                        <div class="dle-block-content !p-0">
                            <ul class="text-[13px]">
                                <li><a href="/" class="block px-4 py-2 border-b border-[#eee] hover:bg-[#f5f5f5] text-gray-700">» All News</a></li>
                                <?php foreach($categories as $c): ?>
                                    <li><a href="/category/<?= htmlspecialchars($c['slug']) ?>" class="block px-4 py-2 border-b border-[#eee] hover:bg-[#f5f5f5] hover:text-[#207cca] text-gray-700 font-medium">» <?= htmlspecialchars($c['name']) ?></a></li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>