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

check_user_auth();
$user_id = $_SESSION['user_id'];

// Fetch Templates: global + user-specific
$templates = [];
try {
    $stmt = $pdo->prepare("SELECT * FROM sms_templates WHERE status = 'active' AND (owner_type = 'admin' OR (owner_type = 'user' AND owner_id = ?)) ORDER BY title");
    $stmt->execute([$user_id]);
    $templates = $stmt->fetchAll() ?: [];
} catch (PDOException $e) {
    try {
        $stmt = $pdo->query("SELECT * FROM sms_templates WHERE status = 'active' ORDER BY title");
        $templates = $stmt->fetchAll() ?: [];
    } catch (PDOException $e2) {
    }
}

$user_groups = get_active_contact_groups('user', $user_id);

$pageTitle = "Send SMS - User Panel";
include '../includes/header.php';
include '../includes/user_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 <small class="text-muted">(Type & Enter for
                                multiple)</small></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($user_groups)): ?>
                                        <option disabled>No Active Groups</option>
                                    <?php else: ?>
                                        <?php foreach ($user_groups as $ug): ?>
                                            <option value="<?php echo $ug['id']; ?>">
                                                <?php echo htmlspecialchars($ug['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>

                    <?php if (!empty($templates)): ?>
                        <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']); ?>
                                        <?php echo ($t['owner_type'] ?? 'admin') === 'admin' ? '(Global)' : '(Mine)'; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    <?php endif; ?>

                    <div class="form-group mb-3">
                        <label class="form-label">Message Body</label>
                        <textarea name="message" id="msgBody" class="form-control" rows="5" required
                            placeholder="Type your message here..."></textarea>
                    </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")); }
        });
    });
    </script>';
include '../includes/footer.php';
?>