<?php
require_once 'includes/header.php';
require_once 'includes/sidebar.php';

$message = '';
$error = '';

// ১. ইউজার ডিলিট করার লজিক (নিরাপত্তার জন্য এডমিন চেকসহ)
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    try {
        // ডিলিট করার আগে চেক করা (ভুল করে নিজেকে বা অন্য এডমিনকে যেন ডিলিট না করে)
        $stmt_check = $pdo->prepare("SELECT role FROM users WHERE id = ?");
        $stmt_check->execute([$id]);
        $u_role = $stmt_check->fetchColumn();

        if ($u_role === 'admin') {
            $error = "নিরাপত্তার স্বার্থে এডমিন ইউজার ডিলিট করা সম্ভব নয়।";
        } else {
            $pdo->prepare("DELETE FROM users WHERE id = ?")->execute([$id]);
            header("Location: manage-users.php?deleted=1");
            exit;
        }
    } catch (PDOException $e) {
        $error = "ইউজার ডিলিট করা যায়নি! হয়তো তার অনেকগুলো অর্ডার ডাটাবেসে আছে।";
    }
}

if (isset($_GET['deleted'])) {
    $message = "ইউজার সফলভাবে মুছে ফেলা হয়েছে।";
}

// ২. পরিসংখ্যান (Stats) বের করা
try {
    $total_cust = $pdo->query("SELECT COUNT(*) FROM users WHERE role = 'customer'")->fetchColumn();
    $new_today = $pdo->query("SELECT COUNT(*) FROM users WHERE role = 'customer' AND DATE(created_at) = CURDATE()")->fetchColumn();
    $with_orders = $pdo->query("SELECT COUNT(DISTINCT user_id) FROM orders WHERE user_id IS NOT NULL")->fetchColumn();
} catch (Exception $e) {}

// ৩. সার্চ লজিক
$search = isset($_GET['q']) ? trim($_GET['q']) : '';
$query_str = "SELECT u.*, COUNT(o.id) as total_orders 
              FROM users u 
              LEFT JOIN orders o ON u.id = o.user_id 
              WHERE u.role = 'customer'";

if (!empty($search)) {
    $query_str .= " AND (u.name LIKE :search OR u.phone LIKE :search OR u.email LIKE :search)";
}

$query_str .= " GROUP BY u.id ORDER BY u.id DESC";

try {
    $stmt = $pdo->prepare($query_str);
    if (!empty($search)) {
        $stmt->bindValue(':search', "%$search%");
    }
    $stmt->execute();
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Error: " . $e->getMessage());
}
?>

<!-- Page Header -->
<div class="mb-8 flex flex-col md:flex-row md:items-center justify-between gap-4">
    <div>
        <h1 class="text-3xl font-bold text-slate-800 font-bangla tracking-tight">কাস্টমার ম্যানেজমেন্ট</h1>
        <p class="text-slate-500 font-bangla mt-1 text-sm">আপনার ওয়েবসাইটের সব রেজিস্টার্ড কাস্টমারদের তালিকা ও অ্যাক্টিভিটি</p>
    </div>
    
    <!-- Search Bar -->
    <form action="" method="GET" class="relative group">
        <input type="text" name="q" value="<?= htmlspecialchars($search) ?>" placeholder="নাম বা মোবাইল দিয়ে খুঁজুন..." 
               class="w-full md:w-80 pl-10 pr-4 py-2.5 bg-white border border-slate-200 rounded-xl shadow-sm focus:ring-2 focus:ring-accent focus:border-accent outline-none transition font-bangla text-sm">
        <span class="absolute inset-y-0 left-0 pl-3 flex items-center text-slate-400 group-focus-within:text-accent transition">
            <i class="fa-solid fa-magnifying-glass"></i>
        </span>
        <?php if(!empty($search)): ?>
            <a href="manage-users.php" class="absolute inset-y-0 right-3 flex items-center text-slate-400 hover:text-red-500">
                <i class="fa-solid fa-circle-xmark"></i>
            </a>
        <?php endif; ?>
    </form>
</div>

<!-- Stats Cards -->
<div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
    <div class="bg-white p-6 rounded-2xl border border-slate-100 shadow-sm flex items-center gap-5">
        <div class="w-12 h-12 bg-blue-50 text-blue-600 rounded-xl flex items-center justify-center text-xl shadow-inner">
            <i class="fa-solid fa-users"></i>
        </div>
        <div>
            <p class="text-xs text-slate-400 font-bold uppercase tracking-wider">মোট কাস্টমার</p>
            <h3 class="text-2xl font-bold text-slate-800 en-font"><?= $total_cust ?></h3>
        </div>
    </div>
    <div class="bg-white p-6 rounded-2xl border border-slate-100 shadow-sm flex items-center gap-5">
        <div class="w-12 h-12 bg-green-50 text-green-600 rounded-xl flex items-center justify-center text-xl shadow-inner">
            <i class="fa-solid fa-user-plus"></i>
        </div>
        <div>
            <p class="text-xs text-slate-400 font-bold uppercase tracking-wider">আজকের নতুন</p>
            <h3 class="text-2xl font-bold text-slate-800 en-font"><?= $new_today ?></h3>
        </div>
    </div>
    <div class="bg-white p-6 rounded-2xl border border-slate-100 shadow-sm flex items-center gap-5">
        <div class="w-12 h-12 bg-purple-50 text-purple-600 rounded-xl flex items-center justify-center text-xl shadow-inner">
            <i class="fa-solid fa-shopping-bag"></i>
        </div>
        <div>
            <p class="text-xs text-slate-400 font-bold uppercase tracking-wider">অর্ডারকারী কাস্টমার</p>
            <h3 class="text-2xl font-bold text-slate-800 en-font"><?= $with_orders ?></h3>
        </div>
    </div>
</div>

<!-- Success/Error Alerts -->
<?php if ($message): ?>
    <div class="bg-emerald-50 text-emerald-600 border border-emerald-100 p-4 rounded-xl mb-6 font-bangla flex items-center gap-3 animate-pulse">
        <i class="fa-solid fa-circle-check text-lg"></i> <?= $message ?>
    </div>
<?php endif; ?>
<?php if ($error): ?>
    <div class="bg-rose-50 text-rose-600 border border-rose-100 p-4 rounded-xl mb-6 font-bangla flex items-center gap-3">
        <i class="fa-solid fa-triangle-exclamation text-lg"></i> <?= $error ?>
    </div>
<?php endif; ?>

<!-- Users Table Card -->
<div class="bg-white rounded-3xl shadow-sm border border-slate-100 overflow-hidden mb-12">
    <div class="overflow-x-auto">
        <table class="w-full text-left border-collapse">
            <thead>
                <tr class="bg-slate-50/50 text-slate-400 text-[11px] uppercase font-bold tracking-widest border-b border-slate-100">
                    <th class="p-5">ইউজার প্রোফাইল</th>
                    <th class="p-5">যোগাযোগ</th>
                    <th class="p-5">মোট অর্ডার</th>
                    <th class="p-5">রেজিস্ট্রেশন</th>
                    <th class="p-5 text-right">অ্যাকশন</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-50 text-sm">
                <?php if(empty($users)): ?>
                    <tr>
                        <td colspan="5" class="p-20 text-center text-slate-400 font-bangla">
                            <i class="fa-solid fa-user-slash text-6xl mb-4 block opacity-10"></i>
                            দুঃখিত! কোনো কাস্টমার খুঁজে পাওয়া যায়নি।
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach($users as $user): ?>
                    <tr class="hover:bg-slate-50/80 transition group">
                        <td class="p-5">
                            <div class="flex items-center gap-4">
                                <div class="w-12 h-12 rounded-full bg-accent/10 text-accent flex items-center justify-center font-bold text-lg border border-accent/20 uppercase en-font">
                                    <?= substr($user['name'], 0, 1) ?>
                                </div>
                                <div>
                                    <h4 class="font-bold text-slate-800 font-bangla text-base"><?= htmlspecialchars($user['name']) ?></h4>
                                    <p class="text-xs text-slate-400 font-bangla line-clamp-1 w-40" title="<?= htmlspecialchars($user['address']) ?>">
                                        <i class="fa-solid fa-location-dot mr-1 text-[10px]"></i> <?= htmlspecialchars($user['address']) ?: 'ঠিকানা নেই' ?>
                                    </p>
                                </div>
                            </div>
                        </td>
                        
                        <td class="p-5">
                            <div class="space-y-1">
                                <a href="tel:<?= $user['phone'] ?>" class="font-bold text-slate-700 en-font flex items-center gap-1 hover:text-accent transition">
                                    <i class="fa-solid fa-phone text-[10px] text-slate-300"></i> <?= htmlspecialchars($user['phone']) ?>
                                </a>
                                <?php if($user['email']): ?>
                                    <p class="text-xs text-slate-400 en-font flex items-center gap-1">
                                        <i class="fa-solid fa-envelope text-[10px] text-slate-300"></i> <?= htmlspecialchars($user['email']) ?>
                                    </p>
                                <?php endif; ?>
                            </div>
                        </td>

                        <td class="p-5">
                            <span class="bg-blue-50 text-blue-700 px-3 py-1 rounded-lg font-bold en-font text-xs border border-blue-100 shadow-sm">
                                <?= $user['total_orders'] ?> Orders
                            </span>
                        </td>

                        <td class="p-5">
                            <p class="text-xs text-slate-500 en-font"><?= date('d M, Y', strtotime($user['created_at'])) ?></p>
                            <p class="text-[10px] text-slate-300 uppercase mt-0.5"><?= date('h:i A', strtotime($user['created_at'])) ?></p>
                        </td>

                        <td class="p-5 text-right">
                            <div class="flex justify-end gap-2">
                                <!-- Details Modal Trigger -->
                                <button onclick='viewUserDetails(<?= json_encode($user) ?>)' class="w-9 h-9 flex items-center justify-center bg-blue-50 text-blue-600 rounded-xl hover:bg-blue-600 hover:text-white transition shadow-sm border border-blue-100" title="বিস্তারিত">
                                    <i class="fa-solid fa-eye"></i>
                                </button>
                                <!-- Delete Button -->
                                <a href="manage-users.php?delete=<?= $user['id'] ?>" onclick="return confirm('আপনি কি নিশ্চিত? এই কাস্টমারের সব ডাটা মুছে যাবে!')" 
                                   class="w-9 h-9 flex items-center justify-center bg-rose-50 text-rose-500 rounded-xl hover:bg-rose-500 hover:text-white transition shadow-sm border border-rose-100" title="ডিলিট">
                                    <i class="fa-solid fa-trash-can"></i>
                                </a>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- USER DETAILS MODAL -->
<div id="userModal" class="fixed inset-0 bg-slate-900/60 z-[100] hidden flex items-center justify-center p-4 backdrop-blur-sm">
    <div class="bg-white rounded-3xl w-full max-w-lg shadow-2xl overflow-hidden transform transition-all scale-95">
        <div class="p-6 bg-slate-50 border-b flex justify-between items-center">
            <h3 class="text-xl font-bold font-bangla text-slate-800">কাস্টমার প্রোফাইল</h3>
            <button onclick="closeUserModal()" class="w-8 h-8 flex items-center justify-center bg-white border rounded-full text-slate-400 hover:text-rose-500 transition shadow-sm"><i class="fa-solid fa-times"></i></button>
        </div>
        
        <div class="p-8">
            <div class="flex flex-col items-center text-center mb-8">
                <div id="modal_avatar" class="w-20 h-20 rounded-3xl bg-accent text-white flex items-center justify-center text-3xl font-bold mb-4 shadow-lg shadow-accent/20 uppercase en-font"></div>
                <h2 id="modal_name" class="text-2xl font-bold text-slate-800 font-bangla"></h2>
                <p class="text-accent font-bold text-sm en-font tracking-wide mt-1 uppercase">Registered Customer</p>
            </div>

            <div class="space-y-5">
                <div class="bg-slate-50 p-4 rounded-2xl border border-slate-100">
                    <p class="text-[10px] text-slate-400 uppercase font-bold mb-2 tracking-widest">কন্টাক্ট ইনফো</p>
                    <div class="grid grid-cols-1 gap-3">
                        <div class="flex items-center gap-3">
                            <i class="fa-solid fa-phone text-accent w-4"></i>
                            <span id="modal_phone" class="text-slate-700 en-font font-bold"></span>
                        </div>
                        <div class="flex items-center gap-3">
                            <i class="fa-solid fa-envelope text-accent w-4"></i>
                            <span id="modal_email" class="text-slate-700 en-font"></span>
                        </div>
                    </div>
                </div>

                <div class="bg-slate-50 p-4 rounded-2xl border border-slate-100">
                    <p class="text-[10px] text-slate-400 uppercase font-bold mb-2 tracking-widest">ডেলিভারি ঠিকানা</p>
                    <div class="flex items-start gap-3">
                        <i class="fa-solid fa-location-dot text-accent w-4 mt-1"></i>
                        <p id="modal_address" class="text-slate-700 font-bangla leading-relaxed text-sm"></p>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="p-6 bg-slate-50 border-t flex justify-center">
            <button onclick="closeUserModal()" class="px-8 py-2.5 bg-slate-800 text-white rounded-xl font-bold font-bangla hover:bg-black transition shadow-lg">বন্ধ করুন</button>
        </div>
    </div>
</div>

<script>
    const modal = document.getElementById('userModal');

    function viewUserDetails(user) {
        document.getElementById('modal_avatar').innerText = user.name.charAt(0);
        document.getElementById('modal_name').innerText = user.name;
        document.getElementById('modal_phone').innerText = user.phone;
        document.getElementById('modal_email').innerText = user.email || 'ইমেইল দেওয়া নেই';
        document.getElementById('modal_address').innerText = user.address || 'ঠিকানা দেওয়া নেই';
        
        modal.classList.remove('hidden');
        modal.querySelector('.bg-white').classList.add('scale-100');
    }

    function closeUserModal() {
        modal.classList.add('hidden');
        modal.querySelector('.bg-white').classList.remove('scale-100');
    }
</script>

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