<?php
session_start();

// Admin Password (Change this to a secure password of your choice)
$admin_password = "tajbihatanha01618411290@@@@"; 

// Login Handler
if (isset($_POST['login'])) {
    if ($_POST['password'] === $admin_password) {
        $_SESSION['iptv_admin'] = true;
    } else {
        $error = "ভুল পাসওয়ার্ড! আবার চেষ্টা করুন।";
    }
}

// Logout Handler
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: admin.php");
    exit;
}

// Paths to data files
$json_file = "../channels.json";
$sources_file = "../sources.json";

// Create files if not exist
if (!file_exists($json_file)) {
    file_put_contents($json_file, json_encode([]));
}
if (!file_exists($sources_file)) {
    // Default fallback M3U sources
    $default_sources = [
        [ "id" => 1, "name" => "সার্ভার ১ (প্রধান)", "url" => "https://raw.githubusercontent.com/imShakil/tvlink/refs/heads/main/iptv.m3u8" ],
        [ "id" => 2, "name" => "আমার লোকাল চ্যানেল", "url" => "channels.json" ]
    ];
    file_put_contents($sources_file, json_encode($default_sources, JSON_PRETTY_PRINT));
}

// Read Channels
$channels = json_decode(file_get_contents($json_file), true);
if (!is_array($channels)) { $channels = []; }

// Read Sources (Servers)
$sources = json_decode(file_get_contents($sources_file), true);
if (!is_array($sources)) { $sources = []; }

$edit_channel = null;
$edit_source = null;

// Handle CRUD operations if logged in
if (isset($_SESSION['iptv_admin']) && $_SESSION['iptv_admin'] === true) {
    
    // ----------------------------------------------------
    // CHANNELS CRUD
    // ----------------------------------------------------
    // Add or Edit Channel
    if (isset($_POST['save_channel'])) {
        $id = $_POST['id'];
        $name = htmlspecialchars($_POST['name']);
        $logo = htmlspecialchars($_POST['logo']);
        $url = htmlspecialchars($_POST['url']);
        $group = htmlspecialchars($_POST['group']);

        if ($id === '') {
            $new_id = time();
            $channels[] = [
                "id" => $new_id,
                "name" => $name,
                "logo" => $logo,
                "url" => $url,
                "group" => $group
            ];
        } else {
            foreach ($channels as &$channel) {
                if ($channel['id'] == $id) {
                    $channel['name'] = $name;
                    $channel['logo'] = $logo;
                    $channel['url'] = $url;
                    $channel['group'] = $group;
                    break;
                }
            }
        }
        file_put_contents($json_file, json_encode(array_values($channels), JSON_PRETTY_PRINT));
        header("Location: admin.php#channels-section");
        exit;
    }

    // Delete Channel
    if (isset($_GET['delete'])) {
        $delete_id = $_GET['delete'];
        $channels = array_filter($channels, function($channel) use ($delete_id) {
            return $channel['id'] != $delete_id;
        });
        file_put_contents($json_file, json_encode(array_values($channels), JSON_PRETTY_PRINT));
        header("Location: admin.php#channels-section");
        exit;
    }

    // Fetch Channel for Edit
    if (isset($_GET['edit'])) {
        $edit_id = $_GET['edit'];
        foreach ($channels as $channel) {
            if ($channel['id'] == $edit_id) {
                $edit_channel = $channel;
                break;
            }
        }
    }

    // ----------------------------------------------------
    // SOURCES (SERVERS) CRUD
    // ----------------------------------------------------
    // Add or Edit Source
    if (isset($_POST['save_source'])) {
        $s_id = $_POST['s_id'];
        $s_name = htmlspecialchars($_POST['s_name']);
        $s_url = htmlspecialchars($_POST['s_url']);

        if ($s_id === '') {
            $sources[] = [
                "id" => time(),
                "name" => $s_name,
                "url" => $s_url
            ];
        } else {
            foreach ($sources as &$src) {
                if ($src['id'] == $s_id) {
                    $src['name'] = $s_name;
                    $src['url'] = $s_url;
                    break;
                }
            }
        }
        file_put_contents($sources_file, json_encode(array_values($sources), JSON_PRETTY_PRINT));
        header("Location: admin.php#sources-section");
        exit;
    }

    // Delete Source
    if (isset($_GET['delete_source'])) {
        $delete_s_id = $_GET['delete_source'];
        $sources = array_filter($sources, function($src) use ($delete_s_id) {
            return $src['id'] != $delete_s_id;
        });
        file_put_contents($sources_file, json_encode(array_values($sources), JSON_PRETTY_PRINT));
        header("Location: admin.php#sources-section");
        exit;
    }

    // Fetch Source for Edit
    if (isset($_GET['edit_source'])) {
        $edit_s_id = $_GET['edit_source'];
        foreach ($sources as $src) {
            if ($src['id'] == $edit_s_id) {
                $edit_source = $src;
                break;
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IPTV অ্যাডমিন প্যানেল</title>
    <style>
        :root {
            --primary-glow: #00d2ff;     /* নিয়নের সায়ান-ব্লু */
            --secondary-glow: #ff5500;   /* নিয়নের অরেঞ্জ-রেড */
            --bg-dark: #070913;          /* গভীর ডার্ক ব্লু */
            --glass-bg: rgba(15, 18, 36, 0.65);
            --glass-border: rgba(255, 255, 255, 0.08);
            --text-color: #ffffff;
            --gray-text: #8c92ac;
        }

        body { 
            font-family: 'Segoe UI', system-ui, -apple-system, sans-serif; 
            background-color: var(--bg-dark); 
            background-image: 
                radial-gradient(circle at 15% 15%, rgba(0, 210, 255, 0.08) 0%, transparent 45%),
                radial-gradient(circle at 85% 85%, rgba(255, 85, 0, 0.08) 0%, transparent 45%);
            margin: 0; 
            padding: 30px 20px; 
            color: var(--text-color); 
            min-height: 100vh;
            box-sizing: border-box;
        }

        .container { 
            max-width: 950px; 
            margin: 0 auto; 
            background: var(--glass-bg); 
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            padding: 30px; 
            border-radius: 16px; 
            border: 1px solid var(--glass-border);
            box-shadow: 0 15px 35px rgba(0,0,0,0.5); 
        }

        h2, h3 { 
            color: #fff; 
            margin-top: 0;
            font-weight: 700;
        }

        h2 {
            font-size: 1.6rem;
            background: linear-gradient(135deg, #fff, var(--primary-glow));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            text-shadow: 0 0 15px rgba(0, 210, 255, 0.35);
            display: inline-block;
        }

        hr {
            border: 0;
            height: 1px;
            background: var(--glass-border);
            margin: 25px 0;
        }

        .form-group { 
            margin-bottom: 20px; 
        }

        label { 
            display: block; 
            margin-bottom: 8px; 
            font-weight: 600; 
            color: var(--gray-text);
            font-size: 0.85rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        input[type="text"], input[type="password"] { 
            width: 100%; 
            padding: 12px 16px; 
            background: rgba(255, 255, 255, 0.03);
            border: 1px solid var(--glass-border); 
            border-radius: 10px; 
            box-sizing: border-box; 
            color: #fff;
            outline: none;
            font-size: 0.95rem;
            transition: all 0.3s ease;
        }

        input[type="text"]:focus, input[type="password"]:focus {
            border-color: var(--primary-glow);
            box-shadow: 0 0 15px rgba(0, 210, 255, 0.25);
            background: rgba(255, 255, 255, 0.06);
        }

        button { 
            background-color: rgba(46, 204, 113, 0.1); 
            border: 1px solid #2ecc71;
            color: #2ecc71; 
            padding: 12px 24px; 
            border-radius: 10px; 
            cursor: pointer; 
            font-size: 0.95rem; 
            font-weight: bold;
            transition: all 0.3s ease;
            outline: none;
        }

        button:hover { 
            background-color: rgba(46, 204, 113, 0.22); 
            box-shadow: 0 0 15px rgba(46, 204, 113, 0.4);
        }

        .logout-btn { 
            background-color: rgba(231, 76, 60, 0.1); 
            border: 1px solid #e74c3c;
            color: #e74c3c;
            float: right; 
            text-decoration: none; 
            padding: 8px 16px; 
            border-radius: 10px; 
            font-weight: bold;
            font-size: 0.88rem;
            transition: all 0.3s ease;
        }

        .logout-btn:hover { 
            background-color: rgba(231, 76, 60, 0.25); 
            box-shadow: 0 0 15px rgba(231, 76, 60, 0.4);
        }

        table { 
            width: 100%; 
            border-collapse: separate; 
            border-spacing: 0 10px; 
            margin-top: 20px; 
        }

        th, td { 
            padding: 14px 16px; 
            text-align: left; 
        }

        th { 
            background-color: transparent; 
            color: var(--gray-text);
            font-size: 0.85rem;
            font-weight: 600;
            text-transform: uppercase;
            border-bottom: 1px solid var(--glass-border);
        }

        td {
            background: rgba(255, 255, 255, 0.02);
            border-top: 1px solid var(--glass-border);
            border-bottom: 1px solid var(--glass-border);
            color: #fff;
            transition: all 0.2s ease;
        }

        td:first-child {
            border-left: 1px solid var(--glass-border);
            border-radius: 12px 0 0 12px;
        }

        td:last-child {
            border-right: 1px solid var(--glass-border);
            border-radius: 0 12px 12px 0;
        }

        tr:hover td {
            background: rgba(255, 255, 255, 0.05);
            border-color: rgba(255, 255, 255, 0.15);
        }

        .btn-edit { 
            background-color: rgba(52, 152, 219, 0.1); 
            border: 1px solid #3498db;
            color: #3498db; 
            text-decoration: none; 
            padding: 6px 12px; 
            border-radius: 8px; 
            margin-right: 5px; 
            font-size: 0.85rem;
            font-weight: bold;
            transition: all 0.2s;
            display: inline-block;
        }

        .btn-edit:hover { 
            background-color: rgba(52, 152, 219, 0.25); 
            box-shadow: 0 0 10px rgba(52, 152, 219, 0.4);
        }

        .btn-delete { 
            background-color: rgba(231, 76, 60, 0.1); 
            border: 1px solid #e74c3c;
            color: #e74c3c; 
            text-decoration: none; 
            padding: 6px 12px; 
            border-radius: 8px; 
            font-size: 0.85rem;
            font-weight: bold;
            transition: all 0.2s;
            display: inline-block;
        }

        .btn-delete:hover { 
            background-color: rgba(231, 76, 60, 0.25); 
            box-shadow: 0 0 10px rgba(231, 76, 60, 0.4);
        }

        .login-box { 
            max-width: 400px; 
            margin: 80px auto; 
            background: var(--glass-bg); 
            border: 1px solid var(--glass-border);
            padding: 40px; 
            border-radius: 16px; 
            box-shadow: 0 15px 35px rgba(0,0,0,0.5); 
            text-align: center;
        }

        .error { 
            background: rgba(231, 76, 60, 0.1);
            border: 1px solid #e74c3c;
            color: #ff5e5e; 
            padding: 10px;
            border-radius: 8px;
            margin-bottom: 20px; 
            font-size: 0.9rem;
        }
    </style>
</head>
<body>

<div class="container">
    <?php if (!isset($_SESSION['iptv_admin'])): ?>
        <!-- Login Form -->
        <div class="login-box">
            <h2 style="margin-bottom: 25px;">অ্যাডমিন লগইন</h2>
            <?php if (isset($error)): ?><div class="error"><?php echo $error; ?></div><?php endif; ?>
            <form method="POST">
                <div class="form-group" style="text-align: left;">
                    <label>পাসওয়ার্ড প্রবেশ করুন</label>
                    <input type="password" name="password" required placeholder="পাসওয়ার্ড লিখুন...">
                </div>
                <button type="submit" name="login" style="width: 100%; margin-top: 10px;">লগইন</button>
            </form>
        </div>
    <?php else: ?>
        <!-- Admin Dashboard -->
        <a href="?logout=1" class="logout-btn">লগআউট</a>
        <h2>IPTV অ্যাডমিন ড্যাশবোর্ড</h2>
        <hr>

        <!-- ========================================================
           ১. সার্ভার সেকশন ম্যানেজমেন্ট (M3U প্লেলিস্ট সোর্স)
           ======================================================== -->
        <div id="sources-section">
            <h3 style="margin-bottom: 20px; font-size: 1.15rem; color: #fff;"><?php echo $edit_source ? 'সার্ভার সংশোধন করুন' : 'নতুন সার্ভার সোর্স যোগ করুন'; ?></h3>
            <form method="POST">
                <input type="hidden" name="s_id" value="<?php echo $edit_source ? $edit_source['id'] : ''; ?>">
                
                <div class="form-group">
                    <label>সার্ভারের নাম</label>
                    <input type="text" name="s_name" value="<?php echo $edit_source ? $edit_source['name'] : ''; ?>" required placeholder="যেমন: সার্ভার ১ (প্রধান)">
                </div>
                
                <div class="form-group">
                    <label>সার্ভার লিংক (M3U8 প্লেলিস্ট বা channels.json লিঙ্ক)</label>
                    <input type="text" name="s_url" value="<?php echo $edit_source ? $edit_source['url'] : ''; ?>" required placeholder="যেমন: https://example.com/iptv.m3u8 বা channels.json">
                </div>

                <button type="submit" name="save_source"><?php echo $edit_source ? 'সার্ভার আপডেট করুন' : 'সার্ভার যোগ করুন'; ?></button>
                <?php if ($edit_source): ?>
                    <a href="admin.php" style="margin-left:15px; text-decoration:none; color: var(--gray-text); font-weight: bold; font-size: 0.9rem;">বাতিল করুন</a>
                <?php endif; ?>
            </form>

            <h3 style="font-size: 1.15rem; color: #fff; margin-top: 30px;">বর্তমান সার্ভার তালিকা (মোট: <?php echo count($sources); ?>)</h3>
            <table>
                <thead>
                    <tr>
                        <th>সার্ভারের নাম</th>
                        <th>সার্ভার লিঙ্ক / ইউআরএল</th>
                        <th style="width: 140px;">অ্যাকশন</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($sources)): ?>
                        <tr><td colspan="3" style="text-align:center;">কোনো সার্ভার পাওয়া যায়নি।</td></tr>
                    <?php else: ?>
                        <?php foreach ($sources as $src): ?>
                            <tr>
                                <td><strong><?php echo $src['name']; ?></strong></td>
                                <td style="word-break: break-all; font-size:0.82rem; color: var(--gray-text);"><?php echo $src['url']; ?></td>
                                <td>
                                    <a href="?edit_source=<?php echo $src['id']; ?>" class="btn-edit" style="border-color: var(--secondary-glow); color: var(--secondary-glow); background: rgba(255,85,0,0.05);">এডিট</a>
                                    <a href="?delete_source=<?php echo $src['id']; ?>" class="btn-delete" onclick="return confirm('আপনি কি নিশ্চিত যে এই সার্ভারটি ডিলিট করতে চান?')">ডিলিট</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <hr style="margin-top:40px; border-color: rgba(255,255,255,0.15);">

        <!-- ========================================================
           ২. কাস্টম চ্যানেল ম্যানেজমেন্ট (লোকাল channels.json)
           ======================================================== -->
        <div id="channels-section">
            <h3 style="margin-bottom: 20px; font-size: 1.15rem; color: #fff;"><?php echo $edit_channel ? 'চ্যানেল সংশোধন করুন' : 'নতুন লোকাল চ্যানেল যোগ করুন'; ?></h3>
            <form method="POST">
                <input type="hidden" name="id" value="<?php echo $edit_channel ? $edit_channel['id'] : ''; ?>">
                
                <div class="form-group">
                    <label>চ্যানেলের নাম</label>
                    <input type="text" name="name" value="<?php echo $edit_channel ? $edit_channel['name'] : ''; ?>" required placeholder="যেমন: Somoy TV">
                </div>
                
                <div class="form-group">
                    <label>লোগো লিঙ্ক (Logo URL)</label>
                    <input type="text" name="logo" value="<?php echo $edit_channel ? $edit_channel['logo'] : ''; ?>" placeholder="যেমন: https://example.com/logo.png">
                </div>

                <div class="form-group">
                    <label>স্ট্রিমিং লিঙ্ক (M3U8 / Stream URL)</label>
                    <input type="text" name="url" value="<?php echo $edit_channel ? $edit_channel['url'] : ''; ?>" required placeholder="যেমন: http://domain.com/live.m3u8">
                </div>

                <div class="form-group">
                    <label>গ্রুপ/ক্যাটাগরি (ঐচ্ছিক)</label>
                    <input type="text" name="group" value="<?php echo $edit_channel ? $edit_channel['group'] : ''; ?>" placeholder="যেমন: News, Entertainment">
                </div>

                <button type="submit" name="save_channel"><?php echo $edit_channel ? 'আপডেট করুন' : 'যোগ করুন'; ?></button>
                <?php if ($edit_channel): ?>
                    <a href="admin.php" style="margin-left:15px; text-decoration:none; color: var(--gray-text); font-weight: bold; font-size: 0.9rem;">বাতিল করুন</a>
                <?php endif; ?>
            </form>

            <h3 style="font-size: 1.15rem; color: #fff; margin-top: 35px;">বর্তমান লোকাল চ্যানেল তালিকা (মোট: <?php echo count($channels); ?>)</h3>
            <table>
                <thead>
                    <tr>
                        <th style="width: 80px;">লোগো</th>
                        <th>নাম</th>
                        <th>ক্যাটাগরি</th>
                        <th>স্ট্রিমিং লিঙ্ক</th>
                        <th style="width: 140px;">অ্যাকশন</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($channels)): ?>
                        <tr><td colspan="5" style="text-align:center;">কোনো চ্যানেল পাওয়া যায়নি।</td></tr>
                    <?php else: ?>
                        <?php foreach ($channels as $channel): 
                            // লোগো লিংক ফাঁকা থাকলে ডাইনামিক ক্যাশেড SVG initials তৈরি হবে
                            $initials = strtoupper(substr(preg_replace('/\s+/', '', $channel['name']), 0, 2));
                            $fallback_svg = "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100' width='100' height='100'><rect width='100' height='100' rx='14' fill='%23141622' stroke='%2300d2ff' stroke-width='2'/><text x='50' y='59' font-family='Segoe UI, sans-serif' font-size='28' font-weight='bold' fill='%23ffffff' text-anchor='middle'>{$initials}</text></svg>";
                            $logo_url = !empty($channel['logo']) ? $channel['logo'] : $fallback_svg;
                        ?>
                            <tr>
                                <td><img src="<?php echo $logo_url; ?>" width="40" height="40" style="object-fit:contain; background:rgba(255,255,255,0.02); border: 1px solid var(--glass-border); border-radius:8px;" onerror="this.onerror=null; this.src='<?php echo $fallback_svg; ?>';"></td>
                                <td><strong><?php echo $channel['name']; ?></strong></td>
                                <td><span style="background: rgba(255,255,255,0.05); padding: 4px 10px; border-radius: 20px; font-size: 0.8rem; border: 1px solid var(--glass-border);"><?php echo $channel['group'] ?: 'General'; ?></span></td>
                                <td style="word-break: break-all; font-size:0.82rem; max-width: 250px; color: var(--gray-text);"><?php echo $channel['url']; ?></td>
                                <td>
                                    <a href="?edit=<?php echo $channel['id']; ?>" class="btn-edit">এডিট</a>
                                    <a href="?delete=<?php echo $channel['id']; ?>" class="btn-delete" onclick="return confirm('আপনি কি নিশ্চিত যে এই চ্যানেলটি ডিলিট করতে চান?')">ডিলিট</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

</body>
</html>