<?php
/**
 * Redirect Manager - Simple Version
 * Qanas - All in one file
 */

// Error reporting
error_reporting(E_ALL);
ini_set('display_errors', '1');

// Session
if (session_id() == '') {
    session_start();
}

// Password
define('ADMIN_PASSWORD', 'qanas2026');

// Data directory
$dataDir = dirname(__FILE__) . '/data/';
if (!is_dir($dataDir)) {
    @mkdir($dataDir, 0755, true);
}

$linksFile = $dataDir . 'links.dat';
$statsFile = $dataDir . 'stats.dat';
$settingsFile = $dataDir . 'settings.dat';

// Helper functions
function loadData($file, $default = array()) {
    if (!file_exists($file)) {
        return $default;
    }
    $content = @file_get_contents($file);
    if (empty($content)) {
        return $default;
    }
    $data = @unserialize($content);
    return is_array($data) ? $data : $default;
}

function saveData($file, $data) {
    @file_put_contents($file, serialize($data), LOCK_EX);
}

function getClientIp() {
    if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
        return $_SERVER['HTTP_CF_CONNECTING_IP'];
    }
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        return trim($ips[0]);
    }
    if (!empty($_SERVER['REMOTE_ADDR'])) {
        return $_SERVER['REMOTE_ADDR'];
    }
    return '0.0.0.0';
}

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

function requireAdmin() {
    if (!isAdmin()) {
        header('Location: ?page=login');
        exit;
    }
}

function getSettings() {
    global $settingsFile;
    $defaults = array(
        'visits_per_link' => 6,
        'rotation_mode' => 'sequential'
    );
    $saved = loadData($settingsFile, array());
    return array_merge($defaults, $saved);
}

function getLinks() {
    global $linksFile;
    return loadData($linksFile, array());
}

function getStats() {
    global $statsFile;
    return loadData($statsFile, array());
}

function addStat($linkId, $linkUrl) {
    global $statsFile;
    $stats = getStats();
    $stats[] = array(
        'time' => date('Y-m-d H:i:s'),
        'ip' => getClientIp(),
        'link_id' => $linkId,
        'link_url' => $linkUrl,
        'date' => date('Y-m-d')
    );
    if (count($stats) > 5000) {
        $stats = array_slice($stats, -5000);
    }
    saveData($statsFile, $stats);
}

function getNextLink() {
    $links = getLinks();
    $settings = getSettings();

    $activeLinks = array();
    foreach ($links as $link) {
        if (isset($link['active']) && $link['active']) {
            $activeLinks[] = $link;
        }
    }

    if (empty($activeLinks)) {
        return null;
    }

    // Sort by order
    usort($activeLinks, 'sortByOrder');

    $visitsPerLink = isset($settings['visits_per_link']) ? intval($settings['visits_per_link']) : 6;
    $visitsPerLink = max(1, $visitsPerLink);

    $stats = getStats();
    $totalVisits = count($stats);

    $totalSlots = count($activeLinks) * $visitsPerLink;
    $currentPosition = $totalVisits % $totalSlots;
    $linkIndex = floor($currentPosition / $visitsPerLink);

    if ($linkIndex >= count($activeLinks)) {
        $linkIndex = 0;
    }

    return isset($activeLinks[$linkIndex]) ? $activeLinks[$linkIndex] : null;
}

function sortByOrder($a, $b) {
    $orderA = isset($a['order']) ? intval($a['order']) : 0;
    $orderB = isset($b['order']) ? intval($b['order']) : 0;
    if ($orderA == $orderB) return 0;
    return ($orderA < $orderB) ? -1 : 1;
}

function getLinkStats($linkId) {
    $stats = getStats();
    $count = 0;
    $today = date('Y-m-d');
    $todayCount = 0;
    foreach ($stats as $stat) {
        if ($stat['link_id'] == $linkId) {
            $count++;
            if ($stat['date'] === $today) {
                $todayCount++;
            }
        }
    }
    return array('total' => $count, 'today' => $todayCount);
}

function getAllStats() {
    $stats = getStats();
    $total = count($stats);
    $today = date('Y-m-d');
    $todayCount = 0;
    $ips = array();
    foreach ($stats as $stat) {
        if ($stat['date'] === $today) {
            $todayCount++;
        }
        $ips[$stat['ip']] = true;
    }
    return array('total' => $total, 'today' => $todayCount, 'unique' => count($ips));
}

function generateId() {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $id = '';
    for ($i = 0; $i < 8; $i++) {
        $id .= $chars[rand(0, strlen($chars) - 1)];
    }
    return $id;
}

// Process actions
$page = isset($_GET['page']) ? $_GET['page'] : 'dashboard';
$action = isset($_POST['action']) ? $_POST['action'] : '';
$message = '';
$messageType = '';

if ($page === 'login') {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['password']) && $_POST['password'] === ADMIN_PASSWORD) {
            $_SESSION['admin_logged_in'] = true;
            header('Location: ?page=dashboard');
            exit;
        } else {
            $message = 'كلمة المرور غير صحيحة!';
            $messageType = 'error';
        }
    }
}

if ($page === 'logout') {
    session_destroy();
    header('Location: ?page=login');
    exit;
}

if ($page !== 'login') {
    requireAdmin();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isAdmin()) {
    if ($action === 'save_link') {
        $links = getLinks();
        $id = isset($_POST['id']) && !empty($_POST['id']) ? $_POST['id'] : generateId();

        $linkData = array(
            'id' => $id,
            'title' => isset($_POST['title']) ? trim($_POST['title']) : '',
            'url' => isset($_POST['url']) ? trim($_POST['url']) : '',
            'order' => isset($_POST['order']) ? intval($_POST['order']) : 0,
            'active' => isset($_POST['active']) ? true : false,
            'created' => date('Y-m-d H:i:s')
        );

        $found = false;
        foreach ($links as $key => $link) {
            if ($link['id'] === $id) {
                $links[$key] = $linkData;
                $found = true;
                break;
            }
        }
        if (!$found) {
            $links[] = $linkData;
        }

        saveData($linksFile, $links);
        $message = 'تم حفظ الرابط!';
        $messageType = 'success';
    }

    if ($action === 'delete_link') {
        $links = getLinks();
        $newLinks = array();
        foreach ($links as $link) {
            if ($link['id'] !== $_POST['id']) {
                $newLinks[] = $link;
            }
        }
        saveData($linksFile, $newLinks);
        $message = 'تم حذف الرابط!';
        $messageType = 'success';
    }

    if ($action === 'save_settings') {
        $settings = array(
            'visits_per_link' => max(1, isset($_POST['visits_per_link']) ? intval($_POST['visits_per_link']) : 6),
            'rotation_mode' => isset($_POST['rotation_mode']) ? $_POST['rotation_mode'] : 'sequential'
        );
        saveData($settingsFile, $settings);
        $message = 'تم حفظ الإعدادات!';
        $messageType = 'success';
    }

    if ($action === 'clear_stats') {
        if (file_exists($statsFile)) {
            @unlink($statsFile);
        }
        $message = 'تم مسح الإحصائيات!';
        $messageType = 'success';
    }

    if ($action === 'change_password') {
        $newPass = isset($_POST['new_password']) ? $_POST['new_password'] : '';
        $confirmPass = isset($_POST['confirm_password']) ? $_POST['confirm_password'] : '';
        if ($newPass === $confirmPass && !empty($newPass)) {
            $configFile = file_get_contents(__FILE__);
            $pattern = "/define\('ADMIN_PASSWORD', '.*'\);/";
            $replacement = "define('ADMIN_PASSWORD', '" . $newPass . "');";
            $configFile = preg_replace($pattern, $replacement, $configFile);
            file_put_contents(__FILE__, $configFile);
            $message = 'تم تغيير كلمة المرور!';
            $messageType = 'success';
        } else {
            $message = 'كلمات المرور غير متطابقة!';
            $messageType = 'error';
        }
    }
}

$links = getLinks();
$settings = getSettings();
$stats = getStats();
$summary = getAllStats();

usort($links, 'sortByOrder');

$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
$redirectUrl = $protocol . '://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/redirect.php';

?><!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>لوحة التحكم - نظام إعادة التوجيه</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: Arial, sans-serif; background: #1a1a2e; color: #fff; min-height: 100vh; }
.login-page { min-height: 100vh; display: flex; align-items: center; justify-content: center; }
.login-box { background: #16213e; border: 1px solid #333; border-radius: 15px; padding: 40px; width: 100%; max-width: 400px; text-align: center; }
.login-box h2 { color: #e94560; margin-bottom: 20px; }
.login-box input { width: 100%; padding: 12px; border: 1px solid #333; border-radius: 8px; background: #0f3460; color: #fff; margin-bottom: 15px; }
.btn { display: inline-block; padding: 10px 20px; border: none; border-radius: 8px; cursor: pointer; text-decoration: none; font-weight: bold; }
.btn-primary { background: #e94560; color: #fff; }
.btn-danger { background: #dc3545; color: #fff; }
.btn-success { background: #28a745; color: #fff; }
.btn-secondary { background: #333; color: #fff; }
.admin-layout { display: flex; }
.sidebar { width: 220px; background: #16213e; position: fixed; right: 0; top: 0; height: 100vh; overflow-y: auto; }
.sidebar-header { padding: 20px; text-align: center; border-bottom: 1px solid #333; }
.sidebar-header h3 { color: #e94560; }
.nav-item { display: block; padding: 12px 20px; color: #aaa; text-decoration: none; border-right: 3px solid transparent; }
.nav-item:hover, .nav-item.active { background: rgba(233,69,96,0.1); color: #e94560; border-right-color: #e94560; }
.main-content { flex: 1; margin-right: 220px; padding: 25px; }
.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 25px; }
.stat-card { background: #16213e; border: 1px solid #333; border-radius: 10px; padding: 20px; text-align: center; }
.stat-card .value { font-size: 1.8em; font-weight: bold; color: #e94560; }
.stat-card .label { color: #888; font-size: 0.9em; }
.content-box { background: #16213e; border: 1px solid #333; border-radius: 10px; padding: 20px; margin-bottom: 20px; }
.content-box h2 { margin-bottom: 15px; color: #e94560; }
.data-table { width: 100%; border-collapse: collapse; }
.data-table th { text-align: right; padding: 10px; color: #888; border-bottom: 2px solid #333; }
.data-table td { padding: 10px; border-bottom: 1px solid #222; color: #ccc; }
.form-group { margin-bottom: 15px; }
.form-group label { display: block; margin-bottom: 5px; color: #ccc; }
.form-control { width: 100%; padding: 10px; border: 1px solid #333; border-radius: 8px; background: #0f3460; color: #fff; }
.alert { padding: 12px; border-radius: 8px; margin-bottom: 20px; }
.alert-success { background: rgba(40,167,69,0.2); border: 1px solid #28a745; color: #28a745; }
.alert-error { background: rgba(220,53,69,0.2); border: 1px solid #dc3545; color: #dc3545; }
.badge { display: inline-block; padding: 3px 10px; border-radius: 15px; font-size: 0.8em; }
.badge-success { background: rgba(40,167,69,0.2); color: #28a745; }
.badge-danger { background: rgba(220,53,69,0.2); color: #dc3545; }
.empty-state { text-align: center; padding: 40px; color: #666; }
.url-cell { max-width: 250px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; direction: ltr; text-align: left; }
.modal-overlay { display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.8); z-index: 1000; align-items: center; justify-content: center; }
.modal-overlay.active { display: flex; }
.modal-box { background: #16213e; border: 1px solid #333; border-radius: 15px; padding: 25px; width: 90%; max-width: 450px; }
.modal-actions { display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px; }
.checkbox-group { display: flex; align-items: center; gap: 10px; margin-bottom: 15px; }
.checkbox-group input { width: 18px; height: 18px; }
@media (max-width: 768px) {
    .sidebar { transform: translateX(100%); }
    .main-content { margin-right: 0; padding: 15px; }
    .stats-grid { grid-template-columns: 1fr 1fr; }
}
</style>
</head>
<body>

<?php if ($page === 'login'): ?>

<div class="login-page">
    <div class="login-box">
        <h2>&#127919; لوحة التحكم</h2>
        <p style="color: #888; margin-bottom: 20px;">نظام إدارة إعادة التوجيه</p>
        <?php if (!empty($message)): ?>
        <div class="alert alert-error"><?php echo $message; ?></div>
        <?php endif; ?>
        <form method="POST" action="?page=login">
            <input type="password" name="password" placeholder="أدخل كلمة المرور" required>
            <button type="submit" class="btn btn-primary" style="width: 100%;">تسجيل الدخول</button>
        </form>
    </div>
</div>

<?php else: ?>

<div class="admin-layout">
    <aside class="sidebar">
        <div class="sidebar-header">
            <h3>&#127919; قناص</h3>
            <p style="color: #888; font-size: 0.8em;">نظام إعادة التوجيه</p>
        </div>
        <nav>
            <a href="?page=dashboard" class="nav-item <?php echo $page === 'dashboard' ? 'active' : ''; ?>">&#128200; الإحصائيات</a>
            <a href="?page=links" class="nav-item <?php echo $page === 'links' ? 'active' : ''; ?>">&#128279; الروابط</a>
            <a href="?page=visits" class="nav-item <?php echo $page === 'visits' ? 'active' : ''; ?>">&#128065; الزيارات</a>
            <a href="?page=settings" class="nav-item <?php echo $page === 'settings' ? 'active' : ''; ?>">&#9881; الإعدادات</a>
            <a href="?page=logout" class="nav-item">&#128682; خروج</a>
        </nav>
    </aside>

    <main class="main-content">

        <?php if (!empty($message)): ?>
        <div class="alert alert-<?php echo $messageType; ?>"><?php echo $message; ?></div>
        <?php endif; ?>

        <?php if ($page === 'dashboard'): ?>

        <h2 style="margin-bottom: 20px;">&#128200; الإحصائيات</h2>

        <div class="stats-grid">
            <div class="stat-card">
                <div class="value"><?php echo number_format($summary['total']); ?></div>
                <div class="label">إجمالي الزيارات</div>
            </div>
            <div class="stat-card">
                <div class="value"><?php echo number_format($summary['today']); ?></div>
                <div class="label">زيارات اليوم</div>
            </div>
            <div class="stat-card">
                <div class="value"><?php echo number_format($summary['unique']); ?></div>
                <div class="label">زوار فريدين</div>
            </div>
            <div class="stat-card">
                <div class="value"><?php echo count($links); ?></div>
                <div class="label">الروابط</div>
            </div>
        </div>

        <div class="content-box">
            <h2>&#128279; أداء الروابط</h2>
            <?php if (empty($links)): ?>
                <div class="empty-state">لا توجد روابط مضافة</div>
            <?php else: ?>
                <table class="data-table">
                    <tr><th>الرابط</th><th>الزيارات</th><th>اليوم</th><th>النسبة</th></tr>
                    <?php foreach ($links as $link): 
                        $linkStats = getLinkStats($link['id']);
                        $percentage = $summary['total'] > 0 ? round(($linkStats['total'] / $summary['total']) * 100, 1) : 0;
                    ?>
                    <tr>
                        <td class="url-cell"><?php echo htmlspecialchars($link['title'] ? $link['title'] : $link['url']); ?></td>
                        <td><strong style="color: #e94560;"><?php echo $linkStats['total']; ?></strong></td>
                        <td><?php echo $linkStats['today']; ?></td>
                        <td><?php echo $percentage; ?>%</td>
                    </tr>
                    <?php endforeach; ?>
                </table>
            <?php endif; ?>
        </div>

        <div class="content-box">
            <h2>&#128279; رابط إعادة التوجيه</h2>
            <p style="color: #888; margin-bottom: 10px;">انسخ هذا الرابط:</p>
            <code style="display: block; padding: 15px; background: #0f3460; border-radius: 8px; color: #e94560; font-size: 0.9em; overflow-x: auto; direction: ltr; text-align: left;">
                <?php echo $redirectUrl; ?>
            </code>
        </div>

        <?php endif; ?>

        <?php if ($page === 'links'): ?>

        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h2>&#128279; إدارة الروابط</h2>
            <button class="btn btn-primary" onclick="document.getElementById('linkModal').classList.add('active')">&#10133; إضافة</button>
        </div>

        <div class="content-box">
            <p style="color: #888; margin-bottom: 15px;">كل <strong style="color: #e94560;"><?php echo $settings['visits_per_link']; ?></strong> زيارات يتم التبديل</p>

            <?php if (empty($links)): ?>
                <div class="empty-state">لا توجد روابط</div>
            <?php else: ?>
                <div style="overflow-x: auto;">
                    <table class="data-table">
                        <tr><th>#</th><th>العنوان</th><th>الرابط</th><th>الترتيب</th><th>الزيارات</th><th>الحالة</th><th></th></tr>
                        <?php foreach ($links as $index => $link): 
                            $linkStats = getLinkStats($link['id']);
                        ?>
                        <tr>
                            <td><?php echo $index + 1; ?></td>
                            <td><?php echo htmlspecialchars($link['title'] ? $link['title'] : 'بدون عنوان'); ?></td>
                            <td class="url-cell"><?php echo htmlspecialchars($link['url']); ?></td>
                            <td><?php echo isset($link['order']) ? $link['order'] : 0; ?></td>
                            <td><strong style="color: #e94560;"><?php echo $linkStats['total']; ?></strong></td>
                            <td><?php echo $link['active'] ? '<span class="badge badge-success">نشط</span>' : '<span class="badge badge-danger">معطل</span>'; ?></td>
                            <td>
                                <form method="POST" style="display: inline;" onsubmit="return confirm('حذف؟')">
                                    <input type="hidden" name="action" value="delete_link">
                                    <input type="hidden" name="id" value="<?php echo $link['id']; ?>">
                                    <button type="submit" class="btn btn-danger btn-sm">&#128465;</button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </table>
                </div>
            <?php endif; ?>
        </div>

        <div class="modal-overlay" id="linkModal">
            <div class="modal-box">
                <h3 style="color: #e94560; margin-bottom: 15px;">&#10133; إضافة رابط</h3>
                <form method="POST">
                    <input type="hidden" name="action" value="save_link">
                    <div class="form-group">
                        <label>العنوان</label>
                        <input type="text" name="title" class="form-control" placeholder="اختياري">
                    </div>
                    <div class="form-group">
                        <label>الرابط *</label>
                        <input type="url" name="url" class="form-control" placeholder="https://example.com" required>
                    </div>
                    <div class="form-group">
                        <label>الترتيب</label>
                        <input type="number" name="order" class="form-control" value="0" min="0">
                    </div>
                    <div class="checkbox-group">
                        <input type="checkbox" name="active" checked>
                        <label>نشط</label>
                    </div>
                    <div class="modal-actions">
                        <button type="button" class="btn btn-secondary" onclick="document.getElementById('linkModal').classList.remove('active')">إلغاء</button>
                        <button type="submit" class="btn btn-primary">حفظ</button>
                    </div>
                </form>
            </div>
        </div>

        <?php endif; ?>

        <?php if ($page === 'visits'): ?>

        <h2 style="margin-bottom: 20px;">&#128065; سجل الزيارات</h2>

        <div class="content-box">
            <?php if (empty($stats)): ?>
                <div class="empty-state">لا توجد زيارات</div>
            <?php else: ?>
                <div style="overflow-x: auto;">
                    <table class="data-table">
                        <tr><th>#</th><th>الوقت</th><th>الرابط</th><th>IP</th></tr>
                        <?php 
                        $reversed = array_reverse($stats);
                        $displayed = array_slice($reversed, 0, 100);
                        foreach ($displayed as $index => $stat): 
                        ?>
                        <tr>
                            <td><?php echo $index + 1; ?></td>
                            <td><?php echo $stat['time']; ?></td>
                            <td class="url-cell"><?php echo htmlspecialchars($stat['link_url']); ?></td>
                            <td style="direction: ltr;"><?php echo $stat['ip']; ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </table>
                </div>
                <?php if (count($stats) > 100): ?>
                <p style="text-align: center; margin-top: 10px; color: #888;">آخر 100 من <?php echo count($stats); ?></p>
                <?php endif; ?>
            <?php endif; ?>
        </div>

        <?php endif; ?>

        <?php if ($page === 'settings'): ?>

        <h2 style="margin-bottom: 20px;">&#9881; الإعدادات</h2>

        <div class="content-box">
            <h3>إعدادات التدوير</h3>
            <form method="POST">
                <input type="hidden" name="action" value="save_settings">
                <div class="form-group">
                    <label>عدد الزيارات لكل رابط</label>
                    <input type="number" name="visits_per_link" class="form-control" value="<?php echo $settings['visits_per_link']; ?>" min="1">
                </div>
                <button type="submit" class="btn btn-primary">حفظ</button>
            </form>
        </div>

        <div class="content-box">
            <h3>تغيير كلمة المرور</h3>
            <form method="POST">
                <input type="hidden" name="action" value="change_password">
                <div class="form-group">
                    <label>كلمة المرور الجديدة</label>
                    <input type="password" name="new_password" class="form-control" required>
                </div>
                <div class="form-group">
                    <label>تأكيد</label>
                    <input type="password" name="confirm_password" class="form-control" required>
                </div>
                <button type="submit" class="btn btn-primary">تغيير</button>
            </form>
        </div>

        <div class="content-box">
            <h3>مسح الإحصائيات</h3>
            <form method="POST" onsubmit="return confirm('متأكد؟')">
                <input type="hidden" name="action" value="clear_stats">
                <button type="submit" class="btn btn-danger">&#128465; مسح</button>
            </form>
        </div>

        <?php endif; ?>

    </main>
</div>

<?php endif; ?>

</body>
</html>