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

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

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

$pageTitle = "Templates - User Panel";
include '../includes/header.php';
include '../includes/user_sidebar.php';
include '../includes/navbar.php';
?>

<div class="page-header">
    <h1 class="page-title">📋 My Templates</h1>
    <div>
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
            <li class="breadcrumb-item active">Templates</li>
        </ol>
    </div>
</div>

<div class="row">
    <div class="col-12 fade-in-up">
        <div class="card">
            <div class="card-header d-flex align-items-center">
                <h3 class="card-title mb-0">Available Templates</h3>
                <small class="ms-auto text-muted"><?php echo count($templates); ?> templates</small>
            </div>
            <div class="card-body">
                <?php if (empty($templates)): ?>
                    <div class="text-center py-5">
                        <i class="fe fe-layers" style="font-size:3rem;color:var(--ui-primary);opacity:0.3;"></i>
                        <p class="text-muted mt-3">No templates available. Ask admin to create templates for you.</p>
                    </div>
                <?php else: ?>
                    <div class="row g-3">
                        <?php foreach ($templates as $t): ?>
                            <div class="col-md-6 col-lg-4">
                                <div class="card h-100" style="border:1px solid rgba(0,0,0,0.08) !important;">
                                    <div class="card-body">
                                        <div class="d-flex align-items-center mb-2">
                                            <h6 class="mb-0 fw-bold"><?php echo htmlspecialchars($t['title']); ?></h6>
                                            <?php if (($t['owner_type'] ?? 'admin') === 'admin'): ?>
                                                <span class="badge-global ms-auto">Global</span>
                                            <?php else: ?>
                                                <span class="badge-user ms-auto">Mine</span>
                                            <?php endif; ?>
                                        </div>
                                        <p class="text-muted mb-3" style="font-size:0.85rem;line-height:1.5;">
                                            <?php echo htmlspecialchars($t['message']); ?>
                                        </p>
                                        <div class="d-flex gap-2">
                                            <button class="btn btn-modern-primary btn-sm flex-grow-1 use-template-btn"
                                                data-message="<?php echo htmlspecialchars($t['message']); ?>">
                                                <i class="fe fe-copy me-1"></i>Copy
                                            </button>
                                            <a href="send_sms.php" class="btn btn-outline-primary btn-sm">
                                                <i class="fe fe-send"></i>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php
$extra_scripts = '
<script>
$(document).ready(function() {
    $(".use-template-btn").click(function() {
        var msg = $(this).data("message");
        navigator.clipboard.writeText(msg).then(function() {
            if (typeof showToast === "function") showToast("Template copied to clipboard!", "success");
            else alert("Copied!");
        });
    });
});
</script>';
include '../includes/footer.php';
?>