<?php
require_once '../config/database.php';
require_once '../config/settings.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

Auth::requireAdmin();
$db = Database::getInstance()->getConnection();
$pageTitle = 'مدیریت پیام‌ها | کیف‌لند';
$success = ''; $error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['reply_message'])) {
        $id    = (int)($_POST['message_id'] ?? 0);
        $reply = trim($_POST['admin_reply'] ?? '');
        if ($id <= 0 || empty($reply)) {
            $error = 'متن پاسخ نمی‌تواند خالی باشد.';
        } else {
            try {
                $db->prepare("UPDATE messages SET admin_reply=?, status='replied', updated_at=NOW() WHERE id=?")->execute([$reply, $id]);
                // ایمیل به کاربر
                $msgStmt = $db->prepare("SELECT m.*, u.email, u.full_name FROM messages m LEFT JOIN users u ON m.user_id=u.id WHERE m.id=?");
                $msgStmt->execute([$id]);
                $msg = $msgStmt->fetch();
                if ($msg && $msg['email']) {
                    emailUserMessageReply($msg['email'], $msg['full_name'], $msg['subject'], $reply);
                }
                Auth::logActivity('admin_message_reply', "پاسخ به پیام #$id");
                $success = 'پاسخ ثبت شد و ایمیل به کاربر ارسال گردید.';
            } catch (Exception $e) { $error = 'خطا: ' . $e->getMessage(); }
        }
    } elseif (isset($_POST['update_status'])) {
        $id     = (int)($_POST['message_id'] ?? 0);
        $status = in_array($_POST['status'], ['unread','read','replied','archived']) ? $_POST['status'] : 'read';
        $db->prepare("UPDATE messages SET status=?, updated_at=NOW() WHERE id=?")->execute([$status, $id]);
        $success = 'وضعیت بروز شد.';
    } elseif (isset($_POST['delete_id'])) {
        $id = (int)$_POST['delete_id'];
        $row = $db->prepare("SELECT attachment FROM messages WHERE id=?");
        $row->execute([$id]);
        $att = $row->fetchColumn();
        if ($att && file_exists('../' . $att)) unlink('../' . $att);
        $db->prepare("DELETE FROM messages WHERE id=?")->execute([$id]);
        $success = 'پیام حذف شد.';
    }
}

$status_filter = $_GET['status'] ?? '';
$search   = trim($_GET['search'] ?? '');
$page     = max(1,(int)($_GET['page'] ?? 1));
$per_page = 15;
$offset   = ($page-1)*$per_page;

$sql = "SELECT m.*, u.full_name FROM messages m LEFT JOIN users u ON m.user_id=u.id WHERE 1=1";
$params = [];
if ($status_filter) { $sql .= " AND m.status=?"; $params[] = $status_filter; }
if ($search !== '') { $sql .= " AND (m.name LIKE ? OR m.email LIKE ? OR m.subject LIKE ? OR m.message LIKE ?)"; $p="%$search%"; array_push($params,$p,$p,$p,$p); }

$count_stmt = $db->prepare(preg_replace('/SELECT m\.\*, u\.full_name/', 'SELECT COUNT(*)', $sql));
$count_stmt->execute($params);
$total = $count_stmt->fetchColumn();
$total_pages = ceil($total/$per_page);

$sql .= " ORDER BY m.created_at DESC LIMIT ? OFFSET ?";
array_push($params,(int)$per_page,(int)$offset);
$stmt = $db->prepare($sql);
$stmt->execute($params);
$messages = $stmt->fetchAll();

// آمار
$stats = $db->query("SELECT status, COUNT(*) as cnt FROM messages GROUP BY status")->fetchAll(PDO::FETCH_KEY_PAIR);

include 'includes/admin-header.php';
?>

<style>
.page-wrap{padding:24px;}
.page-header{margin-bottom:24px;}
.page-header h1{font-size:26px;font-weight:700;margin:0 0 6px;}
.page-header p{color:var(--text-secondary);margin:0;font-size:14px;}
.stats-row{display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin-bottom:24px;}
.stat-card{background:var(--glass-bg);backdrop-filter:blur(20px);border:1px solid var(--glass-border);border-radius:14px;padding:18px;display:flex;align-items:center;gap:14px;}
.stat-icon{width:48px;height:48px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:20px;flex-shrink:0;}
.stat-label{font-size:12px;color:var(--text-secondary);margin-bottom:4px;}
.stat-value{font-size:22px;font-weight:700;}
.alert{padding:12px 16px;border-radius:10px;margin-bottom:18px;display:flex;align-items:center;gap:8px;font-size:14px;}
.alert-success{background:rgba(52,199,89,0.15);color:#0B5D0A;border:1px solid rgba(52,199,89,0.3);}
.alert-danger{background:rgba(255,59,48,0.15);color:#7A1815;border:1px solid rgba(255,59,48,0.3);}
.glass-card{background:var(--glass-bg);backdrop-filter:blur(20px);border:1px solid var(--glass-border);border-radius:16px;overflow:hidden;}
.card-head{padding:18px 20px;border-bottom:1px solid var(--glass-border);display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;}
.card-head h3{margin:0;font-size:17px;font-weight:700;}
.filter-form{display:flex;align-items:center;gap:10px;flex-wrap:wrap;}
.form-ctrl{padding:9px 13px;border:1px solid var(--glass-border);border-radius:9px;font-family:inherit;font-size:13px;background:var(--glass-bg);min-height:40px;}
.form-ctrl:focus{outline:none;border-color:var(--primary);}
.btn{padding:9px 16px;border-radius:9px;border:none;font-weight:600;font-size:13px;cursor:pointer;font-family:inherit;display:inline-flex;align-items:center;gap:6px;min-height:40px;transition:0.2s;}
.btn-primary{background:var(--primary);color:#fff;}
.btn-primary:hover{opacity:0.88;}
.btn-ghost{background:transparent;border:1px solid var(--glass-border);color:var(--text-primary);}
.btn-ghost:hover{background:var(--glass-hover);}
.btn-sm{padding:7px 12px;font-size:12px;min-height:36px;}
.tbl{width:100%;border-collapse:collapse;}
.tbl thead th{text-align:right;padding:13px 16px;font-size:12px;font-weight:600;color:var(--text-secondary);background:rgba(255,255,255,0.3);border-bottom:1px solid var(--glass-border);white-space:nowrap;}
.tbl tbody td{padding:15px 16px;border-bottom:1px solid rgba(255,255,255,0.12);font-size:14px;vertical-align:middle;}
.tbl tbody tr:hover{background:rgba(255,255,255,0.35);}
.tbl tbody tr.unread-row td{font-weight:600;}
.act-btn{width:34px;height:34px;border-radius:8px;border:none;background:rgba(255,255,255,0.3);cursor:pointer;display:inline-flex;align-items:center;justify-content:center;color:var(--text-secondary);transition:0.2s;}
.act-btn:hover.view{color:var(--primary);}
.act-btn:hover.del{color:var(--danger);background:rgba(255,59,48,0.1);}
.badge{font-size:11px;padding:3px 8px;border-radius:20px;font-weight:600;white-space:nowrap;}
.badge-warning{background:#fff3cd;color:#856404;}
.badge-info{background:#d1ecf1;color:#0c5460;}
.badge-success{background:#d4edda;color:#155724;}
.badge-secondary{background:#e2e3e5;color:#383d41;}
.has-att{font-size:11px;padding:2px 7px;border-radius:20px;background:rgba(0,122,255,0.1);color:var(--primary);display:inline-flex;align-items:center;gap:3px;margin-top:3px;}
.avatar{width:36px;height:36px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:13px;flex-shrink:0;background:rgba(0,122,255,0.15);color:var(--primary);}
.name-cell{display:flex;align-items:center;gap:10px;}
.pagination{display:flex;align-items:center;justify-content:center;gap:6px;padding:16px;flex-wrap:wrap;}
.pg-link{min-width:36px;height:36px;display:flex;align-items:center;justify-content:center;background:var(--glass-bg);border:1px solid var(--glass-border);border-radius:8px;font-size:13px;color:var(--text-primary);text-decoration:none;transition:0.2s;}
.pg-link:hover,.pg-link.active{background:var(--primary);color:#fff;border-color:var(--primary);}
/* Modal */
.modal{position:fixed;inset:0;z-index:2000;display:none;align-items:center;justify-content:center;padding:20px;background:rgba(0,0,0,0.4);backdrop-filter:blur(4px);}
.modal.active{display:flex;}
.modal-box{background:var(--glass-bg-light);backdrop-filter:blur(40px);border:1px solid var(--glass-border);border-radius:18px;width:100%;max-width:680px;max-height:90vh;overflow-y:auto;box-shadow:0 12px 48px rgba(0,0,0,0.15);}
.modal-head{padding:18px 22px;border-bottom:1px solid var(--glass-border);display:flex;align-items:center;justify-content:space-between;position:sticky;top:0;background:inherit;z-index:10;border-radius:18px 18px 0 0;}
.modal-head h3{margin:0;font-size:17px;font-weight:700;}
.close-btn{width:36px;height:36px;border-radius:50%;border:none;background:rgba(255,255,255,0.3);cursor:pointer;font-size:18px;display:flex;align-items:center;justify-content:center;transition:0.2s;}
.close-btn:hover{background:rgba(255,59,48,0.15);color:var(--danger);}
.modal-body{padding:22px;}
.modal-foot{padding:14px 22px;border-top:1px solid var(--glass-border);display:flex;justify-content:flex-end;gap:10px;position:sticky;bottom:0;background:inherit;border-radius:0 0 18px 18px;}
.info-box{background:rgba(255,255,255,0.3);border:1px solid var(--glass-border);border-radius:10px;padding:14px 16px;margin-bottom:16px;}
.info-box p{margin:5px 0;font-size:14px;}
.msg-content{background:rgba(255,255,255,0.25);border-radius:10px;padding:14px;font-size:14px;line-height:1.8;white-space:pre-wrap;word-break:break-word;margin-bottom:16px;color:var(--text-primary);}
.prev-reply{background:rgba(0,122,255,0.08);border-right:3px solid var(--primary);border-radius:8px;padding:12px;margin-bottom:16px;font-size:14px;line-height:1.7;}
.att-box{margin-bottom:16px;}
.att-box img{max-width:100%;max-height:240px;border-radius:10px;border:1px solid #ddd;cursor:pointer;object-fit:contain;transition:0.2s;}
.att-box img:hover{opacity:0.85;}
.att-link{display:inline-flex;align-items:center;gap:6px;font-size:13px;color:var(--primary);text-decoration:none;margin-top:6px;}
.form-label{display:block;font-weight:600;font-size:14px;margin-bottom:7px;}
.form-label.req::after{content:'*';color:var(--danger);margin-right:4px;}
textarea.form-ctrl{min-height:120px;resize:vertical;line-height:1.8;width:100%;box-sizing:border-box;}
/* lightbox */
.lb{display:none;position:fixed;inset:0;background:rgba(0,0,0,0.88);z-index:9999;align-items:center;justify-content:center;}
.lb.on{display:flex;}
.lb img{max-width:90vw;max-height:90vh;border-radius:12px;}
.lb-close{position:fixed;top:18px;left:18px;background:#fff;border:none;border-radius:50%;width:38px;height:38px;font-size:20px;cursor:pointer;display:flex;align-items:center;justify-content:center;}
@media(max-width:768px){.stats-row{grid-template-columns:repeat(2,1fr);}.filter-form{flex-direction:column;align-items:stretch;}}
</style>

<main class="main-content">
    <header class="top-header">
        <button class="menu-toggle" id="menuToggle"><i class="fas fa-bars"></i></button>
        <div class="search-box">
            <i class="fas fa-search"></i>
            <input type="text" id="globalSearch" value="<?= htmlspecialchars($search) ?>" placeholder="جستجو در پیام‌ها...">
        </div>
    </header>

    <div class="page-wrap">
        <div class="page-header">
            <h1>📬 مدیریت پیام‌ها</h1>
            <p>بررسی و پاسخ‌دهی به درخواست‌های کاربران</p>
        </div>

        <?php if ($success): ?><div class="alert alert-success"><i class="fas fa-check-circle"></i> <?= htmlspecialchars($success) ?></div><?php endif; ?>
        <?php if ($error):   ?><div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?></div><?php endif; ?>

        <!-- آمار -->
        <div class="stats-row">
            <div class="stat-card">
                <div class="stat-icon" style="background:rgba(255,149,0,0.15);color:#FF9500;"><i class="fas fa-envelope"></i></div>
                <div><div class="stat-label">خوانده‌نشده</div><div class="stat-value"><?= $stats['unread'] ?? 0 ?></div></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background:rgba(0,122,255,0.15);color:var(--primary);"><i class="fas fa-envelope-open"></i></div>
                <div><div class="stat-label">خوانده‌شده</div><div class="stat-value"><?= $stats['read'] ?? 0 ?></div></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background:rgba(52,199,89,0.15);color:#34C759;"><i class="fas fa-reply"></i></div>
                <div><div class="stat-label">پاسخ‌داده‌شده</div><div class="stat-value"><?= $stats['replied'] ?? 0 ?></div></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background:rgba(142,142,147,0.15);color:#8E8E93;"><i class="fas fa-archive"></i></div>
                <div><div class="stat-label">بایگانی</div><div class="stat-value"><?= $stats['archived'] ?? 0 ?></div></div>
            </div>
        </div>

        <div class="glass-card">
            <div class="card-head">
                <h3>لیست پیام‌ها <span style="font-weight:400;font-size:14px;color:var(--text-secondary);">(<?= number_format($total) ?>)</span></h3>
                <form method="GET" class="filter-form">
                    <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" class="form-ctrl" placeholder="جستجو..." style="min-width:140px;">
                    <select name="status" class="form-ctrl" style="min-width:130px;">
                        <option value="">همه</option>
                        <option value="unread"   <?= $status_filter=='unread'  ?'selected':'' ?>>🔴 خوانده‌نشده</option>
                        <option value="read"     <?= $status_filter=='read'    ?'selected':'' ?>>🔵 خوانده‌شده</option>
                        <option value="replied"  <?= $status_filter=='replied' ?'selected':'' ?>>🟢 پاسخ‌داده‌شده</option>
                        <option value="archived" <?= $status_filter=='archived'?'selected':'' ?>>⚫ بایگانی</option>
                    </select>
                    <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-filter"></i> فیلتر</button>
                    <a href="messages.php" class="btn btn-ghost btn-sm"><i class="fas fa-undo"></i></a>
                </form>
            </div>

            <div style="overflow-x:auto;">
                <table class="tbl">
                    <thead>
                        <tr>
                            <th style="width:20%;">فرستنده</th>
                            <th style="width:35%;">موضوع / متن</th>
                            <th style="width:13%;">وضعیت</th>
                            <th style="width:12%;">تاریخ</th>
                            <th style="width:20%;text-align:center;">عملیات</th>
                        </tr>
                    </thead>
                    <tbody id="msgBody">
                        <?php if (!empty($messages)): ?>
                        <?php foreach ($messages as $msg): ?>
                        <tr class="<?= $msg['status']==='unread'?'unread-row':'' ?>">
                            <td>
                                <div class="name-cell">
                                    <div class="avatar"><?= mb_substr($msg['name'],0,1) ?></div>
                                    <div>
                                        <div><?= htmlspecialchars($msg['name']) ?></div>
                                        <small style="color:var(--text-secondary);font-size:12px;"><?= htmlspecialchars($msg['email']) ?></small>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <div style="font-weight:500;margin-bottom:4px;"><?= htmlspecialchars(mb_substr($msg['subject']?:'بدون موضوع',0,45)) ?></div>
                                <small style="color:var(--text-secondary);"><?= htmlspecialchars(mb_substr($msg['message'],0,60)) ?>...</small>
                                <?php if (!empty($msg['attachment'])): ?><div><span class="has-att"><i class="fas fa-paperclip"></i> پیوست</span></div><?php endif; ?>
                            </td>
                            <td>
                                <form method="POST">
                                    <input type="hidden" name="message_id" value="<?= $msg['id'] ?>">
                                    <select name="status" class="form-ctrl" style="padding:5px 8px;font-size:12px;min-width:105px;" onchange="this.form.submit()">
                                        <option value="unread"   <?= $msg['status']=='unread'  ?'selected':'' ?>>🔴 خوانده‌نشده</option>
                                        <option value="read"     <?= $msg['status']=='read'    ?'selected':'' ?>>🔵 خوانده‌شده</option>
                                        <option value="replied"  <?= $msg['status']=='replied' ?'selected':'' ?>>🟢 پاسخ‌داده</option>
                                        <option value="archived" <?= $msg['status']=='archived'?'selected':'' ?>>⚫ بایگانی</option>
                                    </select>
                                    <input type="hidden" name="update_status" value="1">
                                </form>
                            </td>
                            <td style="color:var(--text-secondary);font-size:13px;"><?= jdate($msg['created_at']) ?></td>
                            <td style="text-align:center;">
                                <div style="display:flex;align-items:center;justify-content:center;gap:6px;">
                                    <button class="act-btn view reply-btn"
                                        data-id="<?= $msg['id'] ?>"
                                        data-name="<?= htmlspecialchars($msg['name']) ?>"
                                        data-email="<?= htmlspecialchars($msg['email']) ?>"
                                        data-subject="<?= htmlspecialchars($msg['subject']) ?>"
                                        data-message="<?= htmlspecialchars($msg['message']) ?>"
                                        data-reply="<?= htmlspecialchars($msg['admin_reply']??'') ?>"
                                        data-att="<?= htmlspecialchars($msg['attachment']??'') ?>"
                                        title="مشاهده / پاسخ"><i class="fas fa-reply"></i></button>
                                    <form method="POST" style="display:inline;" onsubmit="return confirm('پیام حذف شود؟');">
                                        <input type="hidden" name="delete_id" value="<?= $msg['id'] ?>">
                                        <button type="submit" class="act-btn del" title="حذف"><i class="fas fa-trash"></i></button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php else: ?>
                        <tr><td colspan="5" style="text-align:center;padding:50px;color:var(--text-secondary);">هیچ پیامی یافت نشد.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <?php if ($total_pages > 1): ?>
            <div class="pagination">
                <?php if ($page>1): ?><a href="?<?= http_build_query(array_merge($_GET,['page'=>$page-1])) ?>" class="pg-link"><i class="fas fa-chevron-right"></i></a><?php endif; ?>
                <?php for($i=1;$i<=$total_pages;$i++): ?>
                    <?php if($i==1||$i==$total_pages||abs($page-$i)<=2): ?>
                    <a href="?<?= http_build_query(array_merge($_GET,['page'=>$i])) ?>" class="pg-link <?= $i==$page?'active':'' ?>"><?= $i ?></a>
                    <?php elseif(abs($page-$i)==3): ?><span style="padding:0 6px;color:var(--text-secondary);">...</span><?php endif; ?>
                <?php endfor; ?>
                <?php if($page<$total_pages): ?><a href="?<?= http_build_query(array_merge($_GET,['page'=>$page+1])) ?>" class="pg-link"><i class="fas fa-chevron-left"></i></a><?php endif; ?>
            </div>
            <?php endif; ?>
        </div>
    </div>
</main>

<!-- Modal پاسخ -->
<div class="modal" id="replyModal">
    <div class="modal-box">
        <form method="POST">
            <div class="modal-head">
                <h3><i class="fas fa-reply" style="color:var(--primary);margin-left:8px;"></i> پاسخ به پیام</h3>
                <button type="button" class="close-btn" onclick="closeModal()">&times;</button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="message_id" id="mId">
                <div class="info-box">
                    <p><strong>از:</strong> <span id="mName"></span> &nbsp;|&nbsp; <span id="mEmail" style="color:var(--text-secondary);font-size:13px;"></span></p>
                    <p><strong>موضوع:</strong> <span id="mSubject"></span></p>
                </div>
                <div class="msg-content" id="mMessage"></div>
                <div class="att-box" id="attBox" style="display:none;">
                    <label class="form-label"><i class="fas fa-paperclip" style="margin-left:6px;"></i>پیوست:</label>
                    <br><img id="attImg" src="" alt="پیوست" onclick="openLb(this.src)">
                    <br><a id="attLink" href="#" target="_blank" class="att-link"><i class="fas fa-external-link-alt"></i> باز در تب جدید</a>
                </div>
                <div class="prev-reply" id="prevReplyBox" style="display:none;">
                    <strong style="color:var(--primary);display:block;margin-bottom:6px;"><i class="fas fa-history"></i> پاسخ قبلی:</strong>
                    <span id="prevReply"></span>
                </div>
                <div>
                    <label class="form-label req">پاسخ شما</label>
                    <textarea name="admin_reply" class="form-ctrl" rows="5" placeholder="پاسخ را بنویسید..." required></textarea>
                </div>
            </div>
            <div class="modal-foot">
                <button type="button" class="btn btn-ghost" onclick="closeModal()">انصراف</button>
                <button type="submit" name="reply_message" class="btn btn-primary"><i class="fas fa-paper-plane"></i> ثبت پاسخ و ارسال ایمیل</button>
            </div>
        </form>
    </div>
</div>

<!-- Lightbox -->
<div class="lb" id="lb" onclick="closeLb()">
    <button class="lb-close" onclick="closeLb()">&times;</button>
    <img id="lbImg" src="" alt="">
</div>

<script src="assets/js/script.js"></script>
<script>
const modal = document.getElementById('replyModal');
document.querySelectorAll('.reply-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        document.getElementById('mId').value      = btn.dataset.id;
        document.getElementById('mName').textContent    = btn.dataset.name;
        document.getElementById('mEmail').textContent   = btn.dataset.email;
        document.getElementById('mSubject').textContent = btn.dataset.subject || 'بدون موضوع';
        document.getElementById('mMessage').textContent = btn.dataset.message;

        const attBox = document.getElementById('attBox');
        if (btn.dataset.att) {
            document.getElementById('attImg').src  = '../' + btn.dataset.att;
            document.getElementById('attLink').href = '../' + btn.dataset.att;
            attBox.style.display = 'block';
        } else { attBox.style.display = 'none'; }

        const prevBox = document.getElementById('prevReplyBox');
        if (btn.dataset.reply) {
            document.getElementById('prevReply').textContent = btn.dataset.reply;
            prevBox.style.display = 'block';
        } else { prevBox.style.display = 'none'; }

        modal.querySelector('textarea').value = '';
        modal.classList.add('active');
        setTimeout(() => modal.querySelector('textarea').focus(), 250);
    });
});
function closeModal() { modal.classList.remove('active'); }
modal.addEventListener('click', e => { if (e.target === modal) closeModal(); });
function openLb(src) { document.getElementById('lbImg').src=src; document.getElementById('lb').classList.add('on'); }
function closeLb()   { document.getElementById('lb').classList.remove('on'); }
document.addEventListener('keydown', e => { if(e.key==='Escape'){closeModal();closeLb();} });

document.getElementById('globalSearch')?.addEventListener('input', function() {
    const t = this.value.toLowerCase();
    document.querySelectorAll('#msgBody tr').forEach(r => r.style.display = r.textContent.toLowerCase().includes(t)?'':'none');
});
</script>
<?php include 'includes/admin-footer.php'; ?>
