<?php
require_once 'admin_init.php';
// === ডিবাগিং এর জন্য এরর রিপোর্টিং চালু করা (শুধু পরীক্ষার জন্য) ===
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// =============================================================

// ১. আপনার বিদ্যমান হেডার ফাইল
require_once 'includes/header.php'; 
$conn = $conn_header; 

// ২. টেলিগ্রাম মেসেজ পাঠানোর ফাংশন (অপরিবর্তিত)
function sendLocalPhotoToUser($botToken, $chatId, $photoPath, $caption) {
    $url = "https://api.telegram.org/bot{$botToken}/sendPhoto";
    if (function_exists('curl_file_create')) {
        $cFile = curl_file_create($photoPath);
    } else {
        $cFile = '@' . realpath($photoPath);
    }
    $post_fields = ['chat_id' => $chatId, 'photo' => $cFile, 'caption' => $caption, 'parse_mode' => 'HTML'];
    $ch = curl_init();
    curl_setopt_array($ch, [CURLOPT_URL => $url, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => $post_fields, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, CURLOPT_SSL_VERIFYPEER => false]);
    $result = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    if ($error) { error_log("cURL Error: " . $error); }
    return json_decode($result, true);
}

// ৩. ফর্ম সাবমিট হলে মূল কাজটি এখানে হবে
$status_message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['broadcast_to_all'])) {
    $caption = trim($_POST['message'] ?? '');
    $uploaded_photo_path = null;

    // --- ফাইল আপলোড হ্যান্ডলিং ---
    if (isset($_FILES['photo_file']) && $_FILES['photo_file']['error'] === UPLOAD_ERR_OK) {
        $target_dir = __DIR__ . "/uploads/"; // সম্পূর্ণ পাথ ব্যবহার করা ভালো
        if (!is_dir($target_dir)) {
            if (!mkdir($target_dir, 0775, true)) {
                die("Failed to create uploads directory...");
            }
        }
        $file_name = uniqid('img_', true) . '_' . basename($_FILES["photo_file"]["name"]);
        $target_file = $target_dir . $file_name;
        
        if (move_uploaded_file($_FILES["photo_file"]["tmp_name"], $target_file)) {
            $uploaded_photo_path = $target_file;
        } else {
            $status_message = '<div class="alert alert-danger">ফাইল আপলোড করার সময় একটি সার্ভার সমস্যা হয়েছে। ফোল্ডার পারমিশন চেক করুন।</div>';
        }
    } else {
        $status_message = '<div class="alert alert-danger">ছবি আপলোড করা হয়নি অথবা আপলোডে ত্রুটি হয়েছে।</div>';
    }

    // ইনপুট ভ্যালিডেশন
    if (empty($caption) || !$uploaded_photo_path) {
        if (empty($status_message)) {
            $status_message = '<div class="alert alert-danger">মেসেজ এবং ছবি, দুটোই আপলোড করতে হবে।</div>';
        }
    } elseif (!defined('BOT_TOKEN') || empty(BOT_TOKEN)) {
        $status_message = '<div class="alert alert-danger">ত্রুটি: BOT_TOKEN সেট করা নেই।</div>';
    } else {
        $result = $conn->query("SELECT chat_id FROM users WHERE status = 'active'");
        
        if ($result && $result->num_rows > 0) {
            $user_chat_ids = array_column($result->fetch_all(MYSQLI_ASSOC), 'chat_id');
            
            echo "<div class='alert alert-info' style='margin:20px;'> মোট " . count($user_chat_ids) . " জন ব্যবহারকারীকে মেসেজ পাঠানো শুরু হয়েছে...</div>";
            ob_flush(); flush();
            ignore_user_abort(true);
            set_time_limit(0);

            $success_count = 0;
            $failed_count = 0;

            foreach ($user_chat_ids as $chat_id) {
                $response = sendLocalPhotoToUser(BOT_TOKEN, $chat_id, $uploaded_photo_path, $caption);
                if (isset($response['ok']) && $response['ok']) {
                    $success_count++;
                } else {
                    $failed_count++;
                    if (isset($response['error_code']) && $response['error_code'] == 403) {
                        $conn->query("UPDATE users SET status = 'inactive' WHERE chat_id = " . intval($chat_id));
                    }
                }
                usleep(100000);
            }
            
            if (file_exists($uploaded_photo_path)) {
                unlink($uploaded_photo_path);
            }
            $status_message = "<div class='alert alert-success'>ব্রডকাস্ট সম্পন্ন!<br>সফল: <b>{$success_count}</b>, ব্যর্থ: <b>{$failed_count}</b>.</div>";
        } else {
            if (file_exists($uploaded_photo_path)) {
                unlink($uploaded_photo_path);
            }
            $status_message = '<div class="alert alert-warning">কোনো অ্যাক্টিভ ব্যবহারকারী পাওয়া যায়নি।</div>';
        }
    }
}
?>

<!-- ======================= HTML এবং CSS (আগের মতোই সুন্দর ডিজাইন) ======================= -->
<style>
    body::before { content: ''; position: fixed; top: -50%; left: -50%; width: 200%; height: 200%; background: radial-gradient(circle at 20% 20%, rgba(108, 99, 255, 0.25), transparent 30%), radial-gradient(circle at 80% 30%, rgba(0, 123, 255, 0.25), transparent 30%), radial-gradient(circle at 50% 80%, rgba(23, 162, 184, 0.25), transparent 30%); animation: animateBackground 20s linear infinite; z-index: -1; filter: blur(100px); }
    @keyframes animateBackground { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
    .broadcast-container { background: rgba(255, 255, 255, 0.5); backdrop-filter: blur(15px); -webkit-backdrop-filter: blur(15px); border: 1px solid rgba(255, 255, 255, 0.2); border-radius: 20px; padding: 40px; max-width: 800px; margin: 20px auto; box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.15); }
    .broadcast-container h2 { color: var(--text-dark); margin-bottom: 30px; text-align: center; font-size: 2em; font-weight: 600; }
    .form-group { margin-bottom: 25px; }
    .form-group label { display: block; margin-bottom: 10px; font-weight: 600; color: #34495e; }
    .file-input-wrapper { position: relative; width: 100%; border: 2px dashed #bdc3c7; border-radius: 10px; padding: 30px; text-align: center; cursor: pointer; transition: border-color 0.3s, background-color 0.3s; }
    .file-input-wrapper:hover { border-color: var(--primary); background-color: rgba(108, 99, 255, 0.05); }
    .file-input-wrapper input[type=file] { position: absolute; width: 100%; height: 100%; top: 0; left: 0; opacity: 0; cursor: pointer; }
    .file-input-icon { font-size: 2.5em; color: var(--primary); margin-bottom: 15px; }
    #file-name { color: #34495e; font-weight: 500; }
    textarea.form-control { width: 100%; min-height: 150px; padding: 15px; border-radius: 10px; border: 1px solid #bdc3c7; background: #fff; color: var(--text-dark); box-sizing: border-box; font-family: inherit; font-size: 1em; transition: border-color 0.3s, box-shadow 0.3s; }
    textarea.form-control:focus { border-color: var(--primary); box-shadow: 0 0 0 3px rgba(108, 99, 255, 0.2); outline: none; }
    .btn-broadcast { display: flex; align-items: center; justify-content: center; gap: 10px; width: 100%; padding: 16px; font-size: 1.2em; font-weight: 600; color: #fff; background: linear-gradient(45deg, #6c63ff, #4a00e0); border: none; border-radius: 12px; cursor: pointer; transition: all 0.3s ease; box-shadow: 0 4px 15px rgba(108, 99, 255, 0.4); }
    .btn-broadcast:hover { transform: translateY(-3px); box-shadow: 0 6px 20px rgba(108, 99, 255, 0.5); }
    .alert { padding: 15px; margin-bottom: 20px; border-radius: 10px; text-align: center; border: 1px solid transparent; }
    .alert-success { background-color: #d1fae5; color: #065f46; border-color: #a7f3d0; }
    .alert-danger { background-color: #fee2e2; color: #991b1b; border-color: #fca5a5; }
    .alert-warning { background-color: #fef3c7; color: #92400e; border-color: #fde68a; }
    .alert-info { background-color: #dbeafe; color: #1e40af; border-color: #bfdbfe; }
    .image-preview { margin-top: 20px; text-align: center; }
    .image-preview img { max-width: 100%; max-height: 300px; border-radius: 15px; border: 2px solid #ddd; display: none; }
</style>

<div class="broadcast-container">
    <h2><i class="fas fa-paper-plane"></i> Broadcast Photo Message</h2>
    
    <?php if (!empty($status_message)) echo $status_message; ?>

    <form method="POST" action="" enctype="multipart/form-data">
        <div class="form-group">
            <label for="photo_file">Upload Photo</label>
            <div class="file-input-wrapper">
                <input type="file" id="photo_file" name="photo_file" accept="image/jpeg, image/png, image/gif" required>
                <div class="file-input-icon"><i class="fas fa-cloud-upload-alt"></i></div>
                <span id="file-name">Click here to choose a file...</span>
            </div>
            <div class="image-preview"><img id="preview" src="" alt="Image Preview"></div>
        </div>
        <div class="form-group">
            <label for="message">Message (Caption)</label>
            <textarea id="message" name="message" class="form-control" placeholder="আপনার মেসেজ এখানে লিখুন..." required></textarea>
        </div>
        <button type="submit" name="broadcast_to_all" class="btn-broadcast">
            <i class="fas fa-satellite-dish"></i> সব ইউজারকে পাঠান
        </button>
    </form>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const fileInput = document.getElementById('photo_file');
        const fileNameSpan = document.getElementById('file-name');
        const previewImage = document.getElementById('preview');
        fileInput.addEventListener('change', function() {
            if (this.files && this.files[0]) {
                const file = this.files[0];
                fileNameSpan.textContent = file.name;
                const reader = new FileReader();
                reader.onload = (e) => {
                    previewImage.src = e.target.result;
                    previewImage.style.display = 'block';
                }
                reader.readAsDataURL(file);
            } else {
                fileNameSpan.innerHTML = 'Click here to choose a file...';
                previewImage.style.display = 'none';
            }
        });
    });
</script>

<?php require_once 'includes/footer.php'; ?>