<?php
require_once '../../config.php';
require_once '../../functions.php';

check_admin_auth();
$admin_id = $_SESSION['admin_id'] ?? 1;

$templates = [];
try {
    $stmt = $pdo->query("SELECT * FROM sms_templates WHERE status = 'active' ORDER BY title");
    if ($stmt)
        $templates = $stmt->fetchAll() ?: [];
} catch (PDOException $e) {
}

$admin_groups = get_active_contact_groups('admin');

$pageTitle = "Send SMS - Admin Panel";
include '../includes/header.php';
include '../includes/sidebar.php';
include '../includes/navbar.php';
?>

<div class="page-header">
    <h1 class="page-title">✉️ Send SMS</h1>
    <div>
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
            <li class="breadcrumb-item active">Send SMS</li>
        </ol>
    </div>
</div>

<div class="row">
    <div class="col-xl-8 col-lg-12 fade-in-up">
        <div class="card">
            <div class="card-header"
                style="background:linear-gradient(135deg,rgba(79,70,229,0.05),rgba(139,92,246,0.05)) !important;">
                <h3 class="card-title mb-0"><i class="fe fe-send me-2" style="color:var(--ui-primary);"></i>Compose
                    Message</h3>
            </div>
            <div class="card-body">
                <form method="POST" id="sendSmsForm" action="<?php echo base_url('public/api/send_sms.php'); ?>">
                    <div class="form-group mb-3">
                        <label class="form-label">Mobile Numbers</label>
                        <select class="form-control select2-show-search" name="mobile_number[]"
                            multiple="multiple"></select>
                    </div>

                    <div class="row">
                        <div class="col-md-8">
                            <div class="form-group mb-3">
                                <label class="form-label">Contact Group (Optional)</label>
                                <select class="form-control" name="contact_group[]" multiple>
                                    <?php if (empty($admin_groups)): ?>
                                        <option disabled>No Active Groups</option>
                                    <?php else: ?>
                                        <?php foreach ($admin_groups as $ag): ?>
                                            <option value="<?php echo $ag['id']; ?>">
                                                <?php echo htmlspecialchars($ag['name']); ?></option>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="form-label">Message Info</label>
                                <div style="font-size:0.8rem;line-height:1.8;">
                                    Encoding: <span id="sms-encoding" class="fw-bold">GSM_7BIT</span><br>
                                    Chars: <span id="sms-count" class="fw-bold">0</span> |
                                    Parts: <span id="sms-parts" class="fw-bold">0</span><br>
                                    Remaining: <span id="sms-remaining" class="fw-bold">160</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-group mb-3">
                        <label class="form-label">Select Template</label>
                        <select class="form-control form-select" id="templateSelect">
                            <option value="">-- Select Template --</option>
                            <?php foreach ($templates as $t): ?>
                                <option value="<?php echo htmlspecialchars($t['message']); ?>">
                                    <?php echo htmlspecialchars($t['title']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group mb-3">
                        <label class="form-label d-flex align-items-center">
                            Message Body
                            <button type="button" class="btn btn-ai-generate btn-sm ms-auto" id="toggleAiPanel">
                                <i class="fe fe-zap"></i> AI Generate
                            </button>
                        </label>
                        <textarea name="message" id="msgBody" class="form-control" rows="5" required></textarea>
                    </div>

                    <!-- AI Panel -->
                    <div class="ai-panel mb-3" id="aiSendPanel" style="display:none;">
                        <div class="ai-header"><i class="fe fe-cpu"></i> AI Message Generator</div>
                        <div class="row mb-2">
                            <div class="col-8">
                                <input type="text" id="aiSendPrompt" class="form-control form-control-sm"
                                    placeholder="Topic: e.g. Flash sale 50% off">
                            </div>
                            <div class="col-4">
                                <button type="button" id="aiSendGen" class="btn btn-ai-generate btn-sm w-100">
                                    <i class="fe fe-zap"></i> Generate
                                </button>
                            </div>
                        </div>
                        <div class="ai-preview-box" id="aiSendPreview" style="display:none;"></div>
                        <button type="button" id="aiSendUse" class="btn btn-modern-success btn-sm w-100 mt-2"
                            style="display:none;">
                            <i class="fe fe-check me-1"></i>Use This Message
                        </button>
                    </div>

                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-modern-primary flex-grow-1">
                            <i class="fe fe-send me-2"></i>Send Message
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php
$extra_scripts = '
    <script src="' . asset_url('assets/js/pages/sms_logic_v4.js') . '"></script>
    <link href="' . asset_url('assets/plugins/select2/css/select2.min.css') . '" rel="stylesheet" />
    <script src="' . asset_url('assets/plugins/select2/select2.full.min.js') . '"></script>
    <script>
    $(document).ready(function() {
        $(".select2-show-search").select2({
            tags: true, tokenSeparators: [",", " "], width: "100%",
            placeholder: "Enter mobile numbers...", minimumInputLength: 1,
            ajax: {
                url: "' . base_url("public/api/search_contacts.php") . '", dataType: "json", delay: 250,
                data: function(p) { return { term: p.term }; },
                processResults: function(d) { return { results: d.results }; }, cache: true
            }
        });
        $("#templateSelect").change(function() {
            var m = $(this).val();
            if (m) { $("#msgBody").val(m); $("#msgBody")[0].dispatchEvent(new Event("input")); }
        });

        // AI Panel
        $("#toggleAiPanel").click(function() { $("#aiSendPanel").slideToggle(); });
        
        $("#aiSendGen").click(function() {
            var prompt = $("#aiSendPrompt").val();
            if (!prompt) { alert("Enter a topic!"); return; }
            var btn = $(this);
            btn.html("<i class=\"fe fe-loader spin\"></i>").prop("disabled", true);
            $.post("' . base_url('public/api/ai_generate.php') . '", {
                action: "generate", prompt: prompt, language: "English", char_limit: 160
            }, function(r) {
                if (r.success) {
                    $("#aiSendPreview").html(r.text).show();
                    $("#aiSendUse").show().data("text", r.text);
                } else {
                    $("#aiSendPreview").html("<span class=\"text-danger\">" + r.error + "</span>").show();
                }
                btn.html("<i class=\"fe fe-zap\"></i> Generate").prop("disabled", false);
            }, "json").fail(function() { btn.html("<i class=\"fe fe-zap\"></i> Generate").prop("disabled", false); });
        });
        
        $("#aiSendUse").click(function() {
            $("#msgBody").val($(this).data("text"));
            $("#msgBody")[0].dispatchEvent(new Event("input"));
            $("#aiSendPanel").slideUp();
        });
    });
    </script>
    <style>.spin{animation:spin 1s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}</style>';
include '../includes/footer.php';
?>