<?php

declare(strict_types=1);

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/module_hub_helpers.php';
require_once __DIR__ . '/../includes/v3_admin_helpers.php';

require_admin_login();
$db = v3_db();
$schema = v3_ensure_schema($db);
foreach (($schema['notes'] ?? []) as $note) {
    set_flash('success', (string)$note);
}

if (is_post()) {
    $action = (string)post('action');

    if ($action === 'save_settings') {
        $enabled = post('referral_enabled') ? '1' : '0';
        $rewardPoints = (string)max(0, (int)post('referral_reward_points', 0));
        $rewardWallet = number_format(max(0, (float)post('referral_reward_wallet', 0)), 2, '.', '');
        $rewardOn = trim((string)post('referral_reward_on', 'first_order'));
        v3_setting_set($db, 'referral_enabled', $enabled, 'v3_referral');
        v3_setting_set($db, 'referral_reward_points', $rewardPoints, 'v3_referral');
        v3_setting_set($db, 'referral_reward_wallet', $rewardWallet, 'v3_referral');
        v3_setting_set($db, 'referral_reward_on', $rewardOn, 'v3_referral');
        set_flash('success', 'تم حفظ إعدادات نظام الإحالة.');
        redirect_to(admin_url('referrals/index.php'));
    }

    if ($action === 'create_referral') {
        $referrerId = (int)post('referrer_customer_id', 0);
        $referredId = (int)post('referred_customer_id', 0);
        $rewardPoints = max(0, (int)post('reward_points', 0));
        $rewardWallet = max(0, (float)post('reward_wallet_amount', 0));
        $note = trim((string)post('note', ''));

        if ($referrerId <= 0 || $referredId <= 0 || $referrerId === $referredId) {
            set_flash('error', 'اختاري مُحيل ومُحال صالحين وبشكل مختلف.');
        } else {
            $refCode = '';
            $stmt = $db?->prepare('SELECT referral_code, phone FROM customers WHERE id = ? LIMIT 1');
            if ($stmt) {
                $stmt->bind_param('i', $referrerId);
                $stmt->execute();
                $res = $stmt->get_result();
                $row = $res instanceof mysqli_result ? $res->fetch_assoc() : null;
                $refCode = preg_replace('/\D+/', '', (string)($row['phone'] ?? '')) ?: (string)($row['referral_code'] ?? '');
                $stmt->close();
            }
            if ($refCode === '') {
                $refCode = v3_generate_referral_code($db, $referrerId);
                $stmt = $db?->prepare('UPDATE customers SET referral_code = ? WHERE id = ?');
                if ($stmt) {
                    $stmt->bind_param('si', $refCode, $referrerId);
                    $stmt->execute();
                    $stmt->close();
                }
            }

            $referralNoteColumn = v3_referrals_has_column($db, 'note') ? 'note' : 'notes';
            $stmt = $db?->prepare("INSERT INTO customer_referrals (referrer_customer_id, referred_customer_id, referral_code, status, reward_points, reward_wallet_amount, {$referralNoteColumn}, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW()) ON DUPLICATE KEY UPDATE referral_code = VALUES(referral_code), reward_points = VALUES(reward_points), reward_wallet_amount = VALUES(reward_wallet_amount), {$referralNoteColumn} = VALUES({$referralNoteColumn})");
            if ($stmt) {
                $status = 'pending';
                $stmt->bind_param('iissids', $referrerId, $referredId, $refCode, $status, $rewardPoints, $rewardWallet, $note);
                $ok = $stmt->execute();
                $stmt->close();
                if ($ok) {
                    $stmt2 = $db->prepare('UPDATE customers SET referred_by_customer_id = ? WHERE id = ? AND (referred_by_customer_id IS NULL OR referred_by_customer_id = 0)');
                    if ($stmt2) {
                        $stmt2->bind_param('ii', $referrerId, $referredId);
                        $stmt2->execute();
                        $stmt2->close();
                    }
                    set_flash('success', 'تم حفظ علاقة الإحالة بنجاح.');
                } else {
                    set_flash('error', 'تعذر حفظ علاقة الإحالة.');
                }
            }
        }
        redirect_to(admin_url('referrals/index.php'));
    }

    if ($action === 'reward_referral') {
        $referralId = (int)post('referral_id', 0);
        $stmt = $db?->prepare('SELECT * FROM customer_referrals WHERE id = ? LIMIT 1');
        if ($stmt) {
            $stmt->bind_param('i', $referralId);
            $stmt->execute();
            $res = $stmt->get_result();
            $ref = $res instanceof mysqli_result ? $res->fetch_assoc() : null;
            $stmt->close();
            if ($ref) {
                $ok1 = true;
                $ok2 = true;
                if ((int)$ref['reward_points'] > 0) {
                    $ok1 = v3_create_loyalty_tx($db, (int)$ref['referrer_customer_id'], (int)$ref['reward_points'], 'credit', 'referral_reward', 'مكافأة إحالة رقم #' . $referralId);
                }
                if ((float)$ref['reward_wallet_amount'] > 0) {
                    $ok2 = v3_create_wallet_tx($db, (int)$ref['referrer_customer_id'], 'credit', (float)$ref['reward_wallet_amount'], 'referral_reward', (string)$referralId, 'مكافأة إحالة رقم #' . $referralId, v3_admin_id());
                }
                if ($ok1 && $ok2) {
                    $status = 'rewarded';
                    $stmt2 = $db->prepare('UPDATE customer_referrals SET status = ?, rewarded_at = NOW() WHERE id = ?');
                    if ($stmt2) {
                        $stmt2->bind_param('si', $status, $referralId);
                        $stmt2->execute();
                        $stmt2->close();
                    }
                    set_flash('success', 'تمت مكافأة الإحالة وتحديث الرصيد/النقاط.');
                } else {
                    set_flash('error', 'صار خلل أثناء منح مكافأة الإحالة.');
                }
            }
        }
        redirect_to(admin_url('referrals/index.php'));
    }
}

$customerMap = v3_customer_name_map($db);
$settings = hub_settings_map($db);
$stats = [
    'total' => hub_table_count($db, 'customer_referrals'),
    'pending' => hub_table_count($db, 'customer_referrals', "status = 'pending'"),
    'rewarded' => hub_table_count($db, 'customer_referrals', "status = 'rewarded'"),
    'converted' => hub_table_count($db, 'customer_referrals', "status = 'converted'"),
];
$totalRewardPoints = (int)hub_fetch_value($db, 'SELECT COALESCE(SUM(reward_points),0) AS c FROM customer_referrals');
$totalRewardWallet = (float)hub_fetch_value($db, 'SELECT COALESCE(SUM(reward_wallet_amount),0) AS c FROM customer_referrals', 'c', 0.0);
$topReferrers = hub_fetch_all($db, "SELECT r.referrer_customer_id, COUNT(*) AS referrals_count, SUM(r.reward_points) AS reward_points, SUM(r.reward_wallet_amount) AS reward_wallet_amount, c.full_name, c.phone FROM customer_referrals r LEFT JOIN customers c ON c.id = r.referrer_customer_id GROUP BY r.referrer_customer_id ORDER BY referrals_count DESC, reward_wallet_amount DESC LIMIT 8");
$recentReferrals = hub_fetch_all($db, "SELECT r.*, c1.full_name AS referrer_name, c1.phone AS referrer_phone, c2.full_name AS referred_name, c2.phone AS referred_phone FROM customer_referrals r LEFT JOIN customers c1 ON c1.id = r.referrer_customer_id LEFT JOIN customers c2 ON c2.id = r.referred_customer_id ORDER BY r.id DESC LIMIT 15");
$page_title = 'V3 - نظام الإحالة';
$flash = get_flash();
require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/sidebar.php';
?>
<div class="nay-dashboard-page">
    <div class="nay-dashboard-main">
        <?php if ($flash): ?>
            <div class="alert alert-<?= e((string)$flash['type']) ?>"><?= e((string)$flash['message']) ?></div>
        <?php endif; ?>

        <div class="nay-dashboard-hero">
            <div>
                <h1>نظام الإحالة</h1>
                <p>من هنا تضبطين منطق الإحالة المعتمد على رقم هاتف المُحيل، وتشوفين أهم المحيلين، وتقدرين تسجلين إحالات أو تمنحين المكافآت يدويًا إذا احتجتي أثناء التجربة والإطلاق.</p>
            </div>
            <div class="nay-actions">
                <a class="nay-btn" href="/app/admin/customers/list.php"><i class="fa-solid fa-users"></i> قائمة الزبائن</a>
                <a class="nay-btn" href="/app/admin/settings/index.php"><i class="fa-solid fa-gear"></i> الإعدادات</a>
            </div>
        </div>

        <div class="nay-stats-grid">
            <div class="nay-card"><div class="nay-stat-label">إجمالي الإحالات</div><div class="nay-stat-value"><?= number_format($stats['total']) ?></div><div class="nay-stat-sub">كل العلاقات المسجلة</div></div>
            <div class="nay-card"><div class="nay-stat-label">بانتظار المكافأة</div><div class="nay-stat-value"><?= number_format($stats['pending']) ?></div><div class="nay-stat-sub">جاهزة للمراجعة</div></div>
            <div class="nay-card"><div class="nay-stat-label">مكافآت مكتملة</div><div class="nay-stat-value"><?= number_format($stats['rewarded']) ?></div><div class="nay-stat-sub">تم منحها فعليًا</div></div>
            <div class="nay-card"><div class="nay-stat-label">إجمالي نقاط المكافآت</div><div class="nay-stat-value"><?= number_format($totalRewardPoints) ?></div><div class="nay-stat-sub">رصيد Loyalty الناتج</div></div>
            <div class="nay-card"><div class="nay-stat-label">إجمالي رصيد المحفظة</div><div class="nay-stat-value"><?= number_format($totalRewardWallet, 2) ?></div><div class="nay-stat-sub">المكافآت النقدية الناتجة</div></div>
        </div>

        <div class="nay-grid-two">
            <div class="nay-card">
                <h3>إعدادات الإحالة</h3>
                <form method="post" class="form-grid" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:14px;">
                    <input type="hidden" name="action" value="save_settings">
                    <label>
                        تفعيل النظام
                        <select name="referral_enabled">
                            <option value="1" <?= (($settings['referral_enabled'] ?? '1') === '1') ? 'selected' : '' ?>>مفعل</option>
                            <option value="0" <?= (($settings['referral_enabled'] ?? '') === '0') ? 'selected' : '' ?>>موقوف</option>
                        </select>
                    </label>
                    <label>
                        مكافأة بالنقاط
                        <input type="number" min="0" name="referral_reward_points" value="<?= e((string)($settings['referral_reward_points'] ?? '0')) ?>">
                    </label>
                    <label>
                        مكافأة بالمحفظة
                        <input type="number" min="0" step="0.01" name="referral_reward_wallet" value="<?= e((string)($settings['referral_reward_wallet'] ?? '0.00')) ?>">
                    </label>
                    <label>
                        وقت استحقاق المكافأة
                        <select name="referral_reward_on">
                            <?php $rewardOn = (string)($settings['referral_reward_on'] ?? 'first_order'); ?>
                            <option value="signup" <?= $rewardOn === 'signup' ? 'selected' : '' ?>>بعد التسجيل مباشرة</option>
                            <option value="first_order" <?= $rewardOn === 'first_order' ? 'selected' : '' ?>>بعد أول طلب</option>
                            <option value="manual" <?= $rewardOn === 'manual' ? 'selected' : '' ?>>يدوي من الأدمن</option>
                        </select>
                    </label>
                    <div style="display:flex;align-items:end;">
                        <button type="submit" class="btn btn-primary"><i class="fa-solid fa-floppy-disk"></i> حفظ الإعدادات</button>
                    </div>
                </form>
            </div>

            <div class="nay-card">
                <h3>تسجيل إحالة يدويًا</h3>
                <form method="post" class="form-grid" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:14px;">
                    <input type="hidden" name="action" value="create_referral">
                    <label>
                        المُحيل
                        <select name="referrer_customer_id" required>
                            <option value="">اختاري الزبون</option>
                            <?php foreach ($customerMap as $id => $label): ?>
                                <option value="<?= (int)$id ?>"><?= e($label) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </label>
                    <label>
                        المُحال
                        <select name="referred_customer_id" required>
                            <option value="">اختاري الزبون</option>
                            <?php foreach ($customerMap as $id => $label): ?>
                                <option value="<?= (int)$id ?>"><?= e($label) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </label>
                    <label>
                        نقاط المكافأة
                        <input type="number" min="0" name="reward_points" value="<?= e((string)($settings['referral_reward_points'] ?? '0')) ?>">
                    </label>
                    <label>
                        رصيد المحفظة
                        <input type="number" step="0.01" min="0" name="reward_wallet_amount" value="<?= e((string)($settings['referral_reward_wallet'] ?? '0.00')) ?>">
                    </label>
                    <label style="grid-column:1/-1;">
                        ملاحظة
                        <textarea name="note" placeholder="مثلاً: إحالة تجريبية من الحملة الافتتاحية"></textarea>
                    </label>
                    <div>
                        <button type="submit" class="btn btn-primary"><i class="fa-solid fa-share-nodes"></i> حفظ الإحالة</button>
                    </div>
                </form>
            </div>
        </div>

        <div class="nay-grid-two">
            <div class="nay-card">
                <h3>أفضل المُحيلين</h3>
                <?php if (!$topReferrers): ?>
                    <div class="nay-empty">ماكو بيانات إحالة كافية حالياً.</div>
                <?php else: ?>
                    <div class="nay-list">
                        <?php foreach ($topReferrers as $row): ?>
                            <div class="nay-list-item">
                                <div>
                                    <strong><?= e((string)($row['full_name'] ?? 'زبون')) ?></strong>
                                    <div class="nay-muted"><?= e((string)($row['phone'] ?? '')) ?></div>
                                </div>
                                <div style="text-align:left;">
                                    <div><strong><?= number_format((int)($row['referrals_count'] ?? 0)) ?></strong> إحالة</div>
                                    <div class="nay-muted">نقاط: <?= number_format((int)($row['reward_points'] ?? 0)) ?> / محفظة: <?= number_format((float)($row['reward_wallet_amount'] ?? 0), 2) ?></div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>

            <div class="nay-card">
                <h3>تذكير تشغيلي</h3>
                <div class="nay-list">
                    <div class="nay-list-item"><span>هاتف الإحالة يعتمد رقم هاتف كل زبون</span><strong>جاهز</strong></div>
                    <div class="nay-list-item"><span>إمكانية مكافأة نقاط + محفظة</span><strong>مدعومة</strong></div>
                    <div class="nay-list-item"><span>ربط الإحالة بالعميل المُحال</span><strong>موجود</strong></div>
                    <div class="nay-list-item"><span>مكان ضبط القيم الافتراضية</span><strong>من هذه الصفحة</strong></div>
                </div>
            </div>
        </div>

        <div class="nay-card">
            <h3>آخر الإحالات</h3>
            <?php if (!$recentReferrals): ?>
                <div class="nay-empty">ماكو إحالات محفوظة لحد الآن.</div>
            <?php else: ?>
                <div class="nay-table-wrap">
                    <table class="nay-table">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>المُحيل</th>
                                <th>المُحال</th>
                                <th>الكود</th>
                                <th>المكافأة</th>
                                <th>الحالة</th>
                                <th>التاريخ</th>
                                <th>إجراء</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($recentReferrals as $row): ?>
                                <tr>
                                    <td><?= (int)$row['id'] ?></td>
                                    <td><?= e((string)($row['referrer_name'] ?? '-')) ?><br><small><?= e((string)($row['referrer_phone'] ?? '')) ?></small></td>
                                    <td><?= e((string)($row['referred_name'] ?? '-')) ?><br><small><?= e((string)($row['referred_phone'] ?? '')) ?></small></td>
                                    <td><span class="pill" dir="ltr"><?= e((string)($row['referral_code'] ?? '-')) ?></span></td>
                                    <td>نقاط: <?= number_format((int)($row['reward_points'] ?? 0)) ?><br>محفظة: <?= number_format((float)($row['reward_wallet_amount'] ?? 0), 2) ?></td>
                                    <td><?= hub_status_badge((string)$row['status'], (string)$row['status'] === 'rewarded' ? 'success' : ((string)$row['status'] === 'cancelled' ? 'warn' : 'info')) ?></td>
                                    <td><?= e((string)($row['created_at'] ?? '-')) ?></td>
                                    <td>
                                        <?php if ((string)$row['status'] !== 'rewarded'): ?>
                                            <form method="post" style="display:inline;">
                                                <input type="hidden" name="action" value="reward_referral">
                                                <input type="hidden" name="referral_id" value="<?= (int)$row['id'] ?>">
                                                <button type="submit" class="btn btn-light">منح المكافأة</button>
                                            </form>
                                        <?php else: ?>
                                            <span class="nay-muted">مكتملة</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
