<?php
// Session Start
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
// ডাটাবেস কানেকশন (এক ফোল্ডার ব্যাকে গিয়ে)
require_once '../config/database.php'; 

$page_title = "Manage Users";

$success_msg = '';
$error_msg = '';

// =========================================================
// 0. Auto Fix Database Column (ম্যাজিক ফিক্স)
// =========================================================
try {
    // যদি balance বা status কলাম না থাকে, তবে অটোমেটিক অ্যাড করে নেবে
    $db->exec("ALTER TABLE `users` ADD COLUMN `balance` DECIMAL(10,2) DEFAULT 0.00 AFTER `password`");
    $db->exec("ALTER TABLE `users` ADD COLUMN `status` ENUM('active', 'suspended') DEFAULT 'active' AFTER `balance`");
} catch(PDOException $e) {
    // কলাম আগে থেকেই থাকলে এরর ইগনোর করবে
}

// =========================================================
// 1. Handle Add Balance Request
// =========================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_balance'])) {
    $user_id = intval($_POST['user_id']);
    $amount = floatval($_POST['amount']);

    if ($amount <= 0) {
        $error_msg = "Please enter a valid amount greater than 0.";
    } else {
        try {
            // ইউজারের ব্যালেন্স আপডেট করা
            $stmt = $db->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
            if ($stmt->execute([$amount, $user_id])) {
                $success_msg = "Successfully added ৳ " . number_format($amount, 2) . " to the user's account!";
            } else {
                $error_msg = "Failed to add balance. Try again.";
            }
        } catch(PDOException $e) {
            $error_msg = "Database Error: " . $e->getMessage();
        }
    }
}

// =========================================================
// 2. Fetch All Users
// =========================================================
$users = [];
try {
    $stmt = $db->query("SELECT * FROM users ORDER BY id DESC");
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    $error_msg = "Failed to load users: " . $e->getMessage();
}

// =========================================================
// হেডার এবং সাইডবার ইনক্লুড করা (../ দিয়ে ফোল্ডার থেকে বের হয়ে)
// =========================================================
require_once '../includes/user_header.php';
require_once '../includes/user_sidebar.php';
?>

<style>
    /* ==========================================
       Premium Light Grid Theme & Page Styles
       ========================================== */
    body {
        background-color: #ffffff !important;
        background-image: 
            linear-gradient(rgba(37, 99, 235, 0.03) 1px, transparent 1px),
            linear-gradient(90deg, rgba(37, 99, 235, 0.03) 1px, transparent 1px) !important;
        background-size: 30px 30px !important;
        color: #1e293b !important;
    }

    .page-header {
        background: #ffffff; border-bottom: 1px solid rgba(15, 23, 42, 0.05);
        padding: 30px 25px; margin-bottom: 30px;
    }

    .content-box {
        background: #ffffff; border-radius: 20px; border: 1px solid rgba(15, 23, 42, 0.05);
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.03); padding: 25px;
    }

    /* Premium Table */
    .premium-table { width: 100%; border-collapse: separate; border-spacing: 0 10px; margin-top: -10px; }
    .premium-table thead th {
        color: #64748b; font-weight: 700; text-transform: uppercase;
        font-size: 12px; letter-spacing: 1px; padding: 0 20px 10px; border: none;
    }
    .premium-table tbody tr { background: #ffffff; box-shadow: 0 2px 10px rgba(0,0,0,0.02); border-radius: 12px; transition: all 0.3s; }
    .premium-table tbody tr:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(37, 99, 235, 0.08); }
    .premium-table tbody td {
        padding: 20px; vertical-align: middle; border: none;
        border-top: 1px solid rgba(15,23,42,0.03); border-bottom: 1px solid rgba(15,23,42,0.03);
    }
    .premium-table tbody td:first-child { border-left: 1px solid rgba(15,23,42,0.03); border-top-left-radius: 12px; border-bottom-left-radius: 12px; }
    .premium-table tbody td:last-child { border-right: 1px solid rgba(15,23,42,0.03); border-top-right-radius: 12px; border-bottom-right-radius: 12px; }

    .user-name { font-size: 16px; font-weight: 800; color: #1e293b; display: block; margin-bottom: 2px; }
    .user-email { font-size: 13px; color: #64748b; font-weight: 500; }
    
    .balance-badge {
        background: rgba(16, 185, 129, 0.1); color: #10b981;
        padding: 8px 15px; border-radius: 50px; font-weight: 800; font-size: 14px;
        display: inline-block;
    }

    .btn-add-balance {
        background: #2563eb; color: white; border: none; padding: 8px 20px;
        border-radius: 50px; font-weight: 700; font-size: 13px; transition: all 0.3s;
    }
    .btn-add-balance:hover { background: #1d4ed8; color: white; transform: translateY(-2px); box-shadow: 0 5px 15px rgba(37, 99, 235, 0.3); }

    /* Search Box */
    .search-filter {
        background: #f8fafc; border: 1px solid rgba(15, 23, 42, 0.1); border-radius: 50px;
        padding: 10px 20px; width: 100%; max-width: 300px; outline: none; transition: all 0.3s; font-size: 14px;
    }
    .search-filter:focus { border-color: #2563eb; background: #ffffff; box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.1); }

    /* Modal Styles */
    .modal-content { border-radius: 20px; border: none; box-shadow: 0 20px 50px rgba(0,0,0,0.1); }
    .modal-header { border-bottom: 1px solid rgba(15,23,42,0.05); padding: 20px 30px; }
    .modal-body { padding: 30px; }
</style>

<div class="main-content flex-grow-1 w-100 d-flex flex-column" style="min-height: calc(100vh - 70px);">
    
    <!-- Page Header -->
    <div class="page-header d-flex justify-content-between align-items-center flex-wrap gap-3">
        <div>
            <h3 class="fw-bold text-dark mb-1">Manage Users</h3>
            <p class="text-muted mb-0" style="font-size: 14px;">View client details and manage account balances.</p>
        </div>
        <div>
            <div class="position-relative">
                <input type="text" id="userSearch" class="search-filter pe-5" placeholder="Search by name or email..." onkeyup="filterUsers()">
                <i class="fa-solid fa-magnifying-glass position-absolute text-muted" style="right: 15px; top: 50%; transform: translateY(-50%);"></i>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="container pb-5">
        
        <?php if($success_msg): ?>
            <div class="alert alert-success border-0 shadow-sm rounded-3"><i class="fa-solid fa-circle-check me-2"></i> <?= $success_msg ?></div>
        <?php endif; ?>
        <?php if($error_msg): ?>
            <div class="alert alert-danger border-0 shadow-sm rounded-3"><i class="fa-solid fa-triangle-exclamation me-2"></i> <?= $error_msg ?></div>
        <?php endif; ?>

        <div class="content-box">
            <div class="table-responsive">
                <table class="table premium-table" id="usersTable">
                    <thead>
                        <tr>
                            <th>User ID</th>
                            <th>Client Info</th>
                            <th>Contact</th>
                            <th>Current Balance</th>
                            <th>Status</th>
                            <th class="text-end">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(!empty($users)): ?>
                            <?php foreach($users as $user): ?>
                                <tr>
                                    <td class="fw-bold text-muted">#<?= $user['id'] ?></td>
                                    <td>
                                        <span class="user-name"><?= htmlspecialchars($user['name']) ?></span>
                                        <?php if(!empty($user['company_name'])): ?>
                                            <span class="badge bg-light text-dark border"><i class="fa-solid fa-building me-1"></i> <?= htmlspecialchars($user['company_name']) ?></span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="user-email"><i class="fa-regular fa-envelope me-1"></i> <?= htmlspecialchars($user['email']) ?></div>
                                        <?php if(!empty($user['phone'])): ?>
                                            <div class="user-email mt-1"><i class="fa-solid fa-phone me-1"></i> <?= htmlspecialchars($user['phone']) ?></div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="balance-badge">৳ <?= number_format($user['balance'], 2) ?></span>
                                    </td>
                                    <td>
                                        <?php if(isset($user['status']) && $user['status'] == 'active'): ?>
                                            <span class="badge bg-success bg-opacity-10 text-success rounded-pill px-3 py-2"><i class="fa-solid fa-circle-check"></i> Active</span>
                                        <?php else: ?>
                                            <span class="badge bg-danger bg-opacity-10 text-danger rounded-pill px-3 py-2"><i class="fa-solid fa-ban"></i> Suspended</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-end">
                                        <button class="btn-add-balance" onclick="openBalanceModal(<?= $user['id'] ?>, '<?= addslashes(htmlspecialchars($user['name'])) ?>', <?= isset($user['balance']) ? $user['balance'] : 0 ?>)">
                                            <i class="fa-solid fa-plus me-1"></i> Add Balance
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="6" class="text-center py-5 text-muted">
                                    <i class="fa-solid fa-users-slash fs-1 mb-3 opacity-50"></i>
                                    <h5 class="fw-bold">No Users Found</h5>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- ==========================================
     ADD BALANCE MODAL
     ========================================== -->
<div class="modal fade" id="addBalanceModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="fw-bold text-dark mb-0"><i class="fa-solid fa-wallet text-primary me-2"></i> Add Funds to Client</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="" method="POST">
                <div class="modal-body">
                    <input type="hidden" name="user_id" id="modal_user_id">
                    
                    <div class="bg-light p-3 rounded-3 mb-4 border text-center">
                        <span class="text-muted d-block" style="font-size: 13px;">Client Name</span>
                        <h5 class="fw-bold text-dark mb-1" id="modal_user_name">Client</h5>
                        <span class="badge bg-primary bg-opacity-10 text-primary">Current Balance: ৳ <span id="modal_current_balance">0.00</span></span>
                    </div>

                    <div class="mb-3">
                        <label class="fw-bold text-dark mb-2">Enter Amount to Add (৳)</label>
                        <div class="input-group">
                            <span class="input-group-text bg-light border-end-0 fw-bold">৳</span>
                            <input type="number" name="amount" class="form-control border-start-0 ps-0" placeholder="e.g. 500" step="0.01" min="1" required style="font-size: 18px;">
                        </div>
                    </div>
                </div>
                <div class="modal-footer border-0 pb-4 px-4 pt-0">
                    <button type="button" class="btn btn-light rounded-pill px-4 fw-bold" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="add_balance" class="btn btn-primary rounded-pill px-4 fw-bold shadow-sm">Confirm & Add</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // Modal Open Logic
    function openBalanceModal(userId, userName, currentBalance) {
        document.getElementById('modal_user_id').value = userId;
        document.getElementById('modal_user_name').innerText = userName;
        document.getElementById('modal_current_balance').innerText = parseFloat(currentBalance).toLocaleString(undefined, {minimumFractionDigits: 2});
        
        var modal = new bootstrap.Modal(document.getElementById('addBalanceModal'));
        modal.show();
    }

    // Live Search Filter Logic
    function filterUsers() {
        let input = document.getElementById("userSearch");
        let filter = input.value.toUpperCase();
        let table = document.getElementById("usersTable");
        let tr = table.getElementsByTagName("tr");

        for (let i = 1; i < tr.length; i++) {
            let tdName = tr[i].getElementsByTagName("td")[1];
            let tdEmail = tr[i].getElementsByTagName("td")[2];
            
            if (tdName || tdEmail) {
                let txtValue = (tdName.textContent || tdName.innerText) + " " + (tdEmail.textContent || tdEmail.innerText);
                if (txtValue.toUpperCase().indexOf(filter) > -1) {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }       
        }
    }
</script>

<?php 
// ফুটার ইনক্লুড করা (../ দিয়ে)
require_once '../includes/user_footer.php'; 
?>