<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once '../config/database.php';
require_once '../includes/functions.php';

if (!isset($_SESSION['user_level']) || $_SESSION['user_level'] != 'admin') {
    header('Location: ../index.php');
    exit;
}

$success = '';
$error = '';

// ============================================================
// ساخت لینک جدید
// ============================================================
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_link'])) {
    try {
        $stmt = $pdo->prepare("INSERT INTO utm_links (name, utm_source, utm_medium, utm_campaign, status, created_by) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $_POST['name'],
            $_POST['utm_source'],
            $_POST['utm_medium'],
            $_POST['utm_campaign'],
            $_POST['status'],
            $_SESSION['user_id']
        ]);
        $success = "✅ لینک با موفقیت ساخته شد";
    } catch(PDOException $e) {
        $error = "❌ خطا: " . $e->getMessage();
    }
}

// ============================================================
// ویرایش لینک
// ============================================================
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['edit_link'])) {
    try {
        $stmt = $pdo->prepare("UPDATE utm_links SET name = ?, utm_source = ?, utm_medium = ?, utm_campaign = ?, status = ? WHERE id = ?");
        $stmt->execute([
            $_POST['name'],
            $_POST['utm_source'],
            $_POST['utm_medium'],
            $_POST['utm_campaign'],
            $_POST['status'],
            $_POST['link_id']
        ]);
        $success = "✅ لینک با موفقیت ویرایش شد";
    } catch(PDOException $e) {
        $error = "❌ خطا: " . $e->getMessage();
    }
}

// ============================================================
// حذف لینک
// ============================================================
if (isset($_GET['delete'])) {
    try {
        $stmt = $pdo->prepare("DELETE FROM utm_links WHERE id = ?");
        $stmt->execute([$_GET['delete']]);
        $success = "✅ لینک با موفقیت حذف شد";
    } catch(PDOException $e) {
        $error = "❌ خطا: " . $e->getMessage();
    }
}

// ============================================================
// دریافت لیست لینک‌ها
// ============================================================
$links = $pdo->query("SELECT * FROM utm_links ORDER BY created_at DESC")->fetchAll();

// ============================================================
// دریافت دانشجویان یک لینک خاص
// ============================================================
$selectedLinkId = $_GET['view'] ?? 0;
$linkStudents = [];
$selectedLinkName = '';
if ($selectedLinkId > 0) {
    $stmt = $pdo->prepare("SELECT * FROM utm_links WHERE id = ?");
    $stmt->execute([$selectedLinkId]);
    $selectedLink = $stmt->fetch();
    if ($selectedLink) {
        $selectedLinkName = $selectedLink['name'];
        $stmt = $pdo->prepare("
            SELECT m.*, e.name as education_name, c.name as course_name, r.name as referral_name, u.fullname as representative_name
            FROM members m 
            LEFT JOIN educations e ON m.education_id = e.id 
            LEFT JOIN courses c ON m.course_id = c.id
            LEFT JOIN referrals r ON m.referral_id = r.id 
            LEFT JOIN users u ON m.representative_id = u.id
            WHERE m.utm_link_id = ?
            ORDER BY m.created_at DESC
        ");
        $stmt->execute([$selectedLinkId]);
        $linkStudents = $stmt->fetchAll();
    }
}

// ============================================================
// آمار کلی
// ============================================================
$totalLinks = count($links);
$activeLinks = count(array_filter($links, fn($l) => $l['status'] == 'active'));
$inactiveLinks = count(array_filter($links, fn($l) => $l['status'] == 'inactive'));
$totalClicks = array_sum(array_column($links, 'clicks'));
$totalRegistrations = array_sum(array_column($links, 'registrations'));
?>
<?php include '../includes/header.php'; ?>

<style>
.stat-card {
    background: white;
    border-radius: 14px;
    padding: 16px 20px;
    border: 1px solid #e9edf2;
    transition: all 0.3s ease;
    height: 100%;
}
.stat-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 25px rgba(0,0,0,0.06);
}
.stat-card .stat-number {
    font-size: 1.6rem;
    font-weight: 700;
    color: #0f172a;
    line-height: 1.2;
}
.stat-card .stat-label {
    color: #94a3b8;
    font-size: 0.8rem;
    font-weight: 500;
}
.table-modern {
    font-size: 0.85rem;
}
.table-modern thead th {
    background: #f8fafc;
    color: #475569;
    font-weight: 600;
    font-size: 0.75rem;
    text-transform: uppercase;
    letter-spacing: 0.3px;
    padding: 10px 14px;
    border-bottom: 2px solid #e9edf2;
}
.table-modern tbody td {
    padding: 10px 14px;
    border-bottom: 1px solid #f1f5f9;
    vertical-align: middle;
}
.table-modern tbody tr:hover {
    background: #f8fafc;
}
</style>

<!-- ============================================================
پیام‌ها
============================================================ -->
<?php if(!empty($success)): ?>
    <div class="alert alert-success"><?php echo $success; ?></div>
<?php endif; ?>
<?php if(!empty($error)): ?>
    <div class="alert alert-danger"><?php echo $error; ?></div>
<?php endif; ?>

<!-- ============================================================
آمار سریع
============================================================ -->
<div class="row g-3 mb-4">
    <div class="col-xl-3 col-lg-3 col-md-6">
        <div class="stat-card"><div class="stat-number"><?php echo toPersianNumbers($totalLinks); ?></div><div class="stat-label">کل لینک‌ها</div></div>
    </div>
    <div class="col-xl-3 col-lg-3 col-md-6">
        <div class="stat-card"><div class="stat-number"><?php echo toPersianNumbers($activeLinks); ?></div><div class="stat-label">فعال</div></div>
    </div>
    <div class="col-xl-3 col-lg-3 col-md-6">
        <div class="stat-card"><div class="stat-number"><?php echo toPersianNumbers($totalClicks); ?></div><div class="stat-label">کل کلیک‌ها</div></div>
    </div>
    <div class="col-xl-3 col-lg-3 col-md-6">
        <div class="stat-card"><div class="stat-number"><?php echo toPersianNumbers($totalRegistrations); ?></div><div class="stat-label">کل ثبت‌نام‌ها</div></div>
    </div>
</div>

<!-- ============================================================
فرم ساخت لینک جدید
============================================================ -->
<div class="card mb-4">
    <div class="card-header"><i class="bi bi-plus-circle"></i> ساخت لینک جدید</div>
    <div class="card-body">
        <form method="POST" class="row g-2">
            <div class="col-md-2">
                <input type="text" name="name" class="form-control" placeholder="نام کانال" required>
            </div>
            <div class="col-md-2">
                <input type="text" name="utm_source" class="form-control" placeholder="utm_source" required>
            </div>
            <div class="col-md-2">
                <input type="text" name="utm_medium" class="form-control" placeholder="utm_medium" required>
            </div>
            <div class="col-md-2">
                <input type="text" name="utm_campaign" class="form-control" placeholder="utm_campaign" required>
            </div>
            <div class="col-md-2">
                <select name="status" class="form-select">
                    <option value="active">فعال</option>
                    <option value="inactive">غیرفعال</option>
                </select>
            </div>
            <div class="col-md-2">
                <button type="submit" name="add_link" class="btn btn-pastel w-100"><i class="bi bi-plus-lg"></i> ساخت</button>
            </div>
        </form>
    </div>
</div>

<!-- ============================================================
لیست لینک‌ها
============================================================ -->
<div class="card mb-4">
    <div class="card-header"><i class="bi bi-list"></i> لیست لینک‌ها</div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-modern mb-0">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>نام</th>
                        <th>utm_source</th>
                        <th>utm_medium</th>
                        <th>utm_campaign</th>
                        <th>لینک</th>
                        <th>وضعیت</th>
                        <th>کلیک</th>
                        <th>ثبت‌نام</th>
                        <th>عملیات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $counter = 1; ?>
                    <?php foreach ($links as $link): ?>
                    <tr>
                        <td><?php echo toPersianNumbers($counter++); ?></td>
                        <td><?php echo htmlspecialchars($link['name']); ?></td>
                        <td><?php echo htmlspecialchars($link['utm_source']); ?></td>
                        <td><?php echo htmlspecialchars($link['utm_medium']); ?></td>
                        <td><?php echo htmlspecialchars($link['utm_campaign']); ?></td>
                        <td>
                            <input type="text" class="form-control form-control-sm" 
                                   value="https://mehdionline.ir/portal/register.php?utm_source=<?php echo urlencode($link['utm_source']); ?>&utm_medium=<?php echo urlencode($link['utm_medium']); ?>&utm_campaign=<?php echo urlencode($link['utm_campaign']); ?>&utm_link_id=<?php echo $link['id']; ?>" 
                                   readonly>
                        </td>
                        <td>
                            <span class="badge bg-<?php echo $link['status'] == 'active' ? 'success' : 'danger'; ?>">
                                <?php echo $link['status'] == 'active' ? 'فعال' : 'غیرفعال'; ?>
                            </span>
                        </td>
                        <td><?php echo toPersianNumbers($link['clicks']); ?></td>
                        <td><?php echo toPersianNumbers($link['registrations']); ?></td>
                        <td>
                            <a href="?view=<?php echo $link['id']; ?>" class="btn btn-sm btn-info"><i class="bi bi-eye"></i></a>
                            <button class="btn btn-sm btn-primary" data-bs-toggle="collapse" data-bs-target="#editLink<?php echo $link['id']; ?>"><i class="bi bi-pencil"></i></button>
                            <a href="?delete=<?php echo $link['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('آیا از حذف این لینک مطمئن هستید؟')"><i class="bi bi-trash"></i></a>
                            
                            <div class="collapse mt-2" id="editLink<?php echo $link['id']; ?>">
                                <form method="POST" class="row g-1">
                                    <input type="hidden" name="link_id" value="<?php echo $link['id']; ?>">
                                    <div class="col-md-3">
                                        <input type="text" name="name" class="form-control form-control-sm" value="<?php echo htmlspecialchars($link['name']); ?>" required>
                                    </div>
                                    <div class="col-md-3">
                                        <input type="text" name="utm_source" class="form-control form-control-sm" value="<?php echo htmlspecialchars($link['utm_source']); ?>" required>
                                    </div>
                                    <div class="col-md-2">
                                        <input type="text" name="utm_medium" class="form-control form-control-sm" value="<?php echo htmlspecialchars($link['utm_medium']); ?>" required>
                                    </div>
                                    <div class="col-md-2">
                                        <input type="text" name="utm_campaign" class="form-control form-control-sm" value="<?php echo htmlspecialchars($link['utm_campaign']); ?>" required>
                                    </div>
                                    <div class="col-md-1">
                                        <select name="status" class="form-select form-select-sm">
                                            <option value="active" <?php echo $link['status'] == 'active' ? 'selected' : ''; ?>>فعال</option>
                                            <option value="inactive" <?php echo $link['status'] == 'inactive' ? 'selected' : ''; ?>>غیرفعال</option>
                                        </select>
                                    </div>
                                    <div class="col-md-1">
                                        <button type="submit" name="edit_link" class="btn btn-sm btn-success w-100">ذخیره</button>
                                    </div>
                                </form>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- ============================================================
نمایش دانشجویان یک لینک خاص
============================================================ -->
<?php if ($selectedLinkId > 0 && !empty($linkStudents)): ?>
<div class="card">
    <div class="card-header">
        <i class="bi bi-people"></i> دانشجویان ثبت‌نام شده با لینک: <?php echo htmlspecialchars($selectedLinkName); ?>
        <a href="utm_links.php" class="btn btn-sm btn-secondary float-start">🔙 بازگشت</a>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-modern mb-0">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>نام</th>
                        <th>کد ملی</th>
                        <th>تلفن</th>
                        <th>مقطع</th>
                        <th>رشته</th>
                        <th>وضعیت کلی</th>
                        <th>وضعیت تماس</th>
                        <th>وضعیت مدارک</th>
                        <th>وضعیت پرداخت</th>
                        <th>معرف‌کننده</th>
                        <th>دستگاه</th>
                        <th>IP</th>
                        <th>تاریخ ثبت</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $counter = 1; ?>
                    <?php foreach ($linkStudents as $row): ?>
                    <tr>
                        <td><?php echo toPersianNumbers($counter++); ?></td>
                        <td><?php echo htmlspecialchars($row['fullname']); ?></td>
                        <td><?php echo toPersianNumbers($row['national_code']); ?></td>
                        <td><?php echo toPersianNumbers($row['phone']); ?></td>
                        <td><?php echo htmlspecialchars($row['education_name']); ?></td>
                        <td><?php echo htmlspecialchars($row['course_name']); ?></td>
                        <td>
                            <span class="badge bg-<?php echo getStatusColor($row['status']); ?>">
                                <?php echo getStatusLabel($row['status']); ?>
                            </span>
                        </td>
                        <td>
                            <span class="badge bg-<?php echo getContactStatusColor($row['registration_status']); ?>">
                                <?php echo htmlspecialchars($row['registration_status']); ?>
                            </span>
                        </td>
                        <td>
                            <span class="badge bg-<?php echo getDocumentStatusColor($row['document_status']); ?>">
                                <?php echo htmlspecialchars($row['document_status']); ?>
                            </span>
                        </td>
                        <td>
                            <span class="badge bg-<?php echo $row['payment_status'] == 'پرداخت شده' ? 'success' : ($row['payment_status'] == 'پرداخت نشده' ? 'danger' : ($row['payment_status'] == 'عودت وجه' ? 'warning' : 'info')); ?>">
                                <?php echo htmlspecialchars($row['payment_status']); ?>
                            </span>
                        </td>
                        <td><?php echo getRepresentativeName($row['representative_id']); ?></td>
                        <td>
                            <?php 
                            $deviceLabels = ['mobile' => 'موبایل', 'desktop' => 'کامپیوتر', 'tablet' => 'تبلت', 'unknown' => 'نامشخص'];
                            echo $deviceLabels[$row['device_type']] ?? 'نامشخص';
                            ?>
                        </td>
                        <td><?php echo htmlspecialchars($row['ip_address']); ?></td>
                        <td><?php echo convertToPersianDateFa($row['created_at']); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php elseif ($selectedLinkId > 0 && empty($linkStudents)): ?>
<div class="alert alert-info">
    <i class="bi bi-info-circle me-1"></i> هیچ دانشجویی با این لینک ثبت‌نام نکرده است.
    <a href="utm_links.php" class="btn btn-sm btn-secondary ms-2">🔙 بازگشت</a>
</div>
<?php endif; ?>

<?php include '../includes/footer.php'; ?>