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

require_once "../db.php";

/* ================== ADMIN AUTH ================== */
if (!isset($_SESSION['admin'])) {
    header("Location: admin_login.php");
    exit();
}

/* ================== ADD CUSTOMER ================== */
if (isset($_POST['add_customer'])) {
    $name  = trim($_POST['full_name']);
    $phone = trim($_POST['phone']);
    $email = trim($_POST['email']);
    $pass  = trim($_POST['password']);

    if ($name && $phone && $email && $pass) {
        $stmt = $conn->prepare("
            INSERT INTO customers (full_name, phone, email, password, is_active, created_at)
            VALUES (?,?,?,?,1,NOW())
        ");
        $stmt->bind_param("ssss", $name, $phone, $email, $pass);
        $stmt->execute();
        $stmt->close();
    }
    header("Location: users.php");
    exit();
}

/* ================== EXPORT CSV ================== */
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    header("Content-Type: text/csv");
    header("Content-Disposition: attachment; filename=customers.csv");

    $out = fopen("php://output", "w");
    fputcsv($out, ['ID','Full Name','Phone','Email','Password','Balance','Created At']);

    $sql = "
        SELECT c.id, c.full_name, c.phone, c.email, c.password, c.created_at,
        IFNULL(SUM(b.amount),0) balance
        FROM customers c
        LEFT JOIN balance b ON b.user=c.id
        WHERE c.is_active=1
        GROUP BY c.id
        ORDER BY c.id DESC
    ";
    $res = $conn->query($sql);
    while ($row = $res->fetch_assoc()) {
        fputcsv($out, $row);
    }
    fclose($out);
    exit();
}

/* ================== SOFT DELETE ================== */
if (isset($_POST['deactivate_id'])) {
    $id = (int)$_POST['deactivate_id'];
    $stmt = $conn->prepare("UPDATE customers SET is_active=0 WHERE id=?");
    $stmt->bind_param("i",$id);
    $stmt->execute();
    $stmt->close();
    header("Location: users.php");
    exit();
}

/* ================== FUND USER ================== */
if (isset($_POST['fund_user'])) {
    $uid = (int)$_POST['user_id'];
    $amount = (float)$_POST['amount'];

    if ($amount > 0) {
        $stmt = $conn->prepare("
            INSERT INTO balance (user,amount)
            VALUES (?,?)
            ON DUPLICATE KEY UPDATE amount = amount + VALUES(amount)
        ");
        $stmt->bind_param("id",$uid,$amount);
        $stmt->execute();
        $stmt->close();
    }
    header("Location: users.php");
    exit();
}

/* ================== PAGINATION ================== */
$limit = 20;
$page = max(1, (int)($_GET['page'] ?? 1));
$offset = ($page - 1) * $limit;
$search = trim($_GET['search'] ?? '');

/* ================== COUNT ================== */
if ($search !== '') {
    $like = "%$search%";
    $stmt = $conn->prepare("
        SELECT COUNT(*) FROM customers
        WHERE is_active=1
        AND (full_name LIKE ? OR phone LIKE ? OR email LIKE ?)
    ");
    $stmt->bind_param("sss",$like,$like,$like);
} else {
    $stmt = $conn->prepare("SELECT COUNT(*) FROM customers WHERE is_active=1");
}
$stmt->execute();
$stmt->bind_result($total);
$stmt->fetch();
$stmt->close();
$totalPages = ceil($total / $limit);

/* ================== FETCH CUSTOMERS ================== */
if ($search !== '') {
    $stmt = $conn->prepare("
        SELECT c.*, IFNULL(SUM(b.amount),0) balance
        FROM customers c
        LEFT JOIN balance b ON b.user=c.id
        WHERE c.is_active=1
        AND (c.full_name LIKE ? OR c.phone LIKE ? OR c.email LIKE ?)
        GROUP BY c.id
        ORDER BY c.id DESC
        LIMIT ? OFFSET ?
    ");
    $stmt->bind_param("sssii",$like,$like,$like,$limit,$offset);
} else {
    $stmt = $conn->prepare("
        SELECT c.*, IFNULL(SUM(b.amount),0) balance
        FROM customers c
        LEFT JOIN balance b ON b.user=c.id
        WHERE c.is_active=1
        GROUP BY c.id
        ORDER BY c.id DESC
        LIMIT ? OFFSET ?
    ");
    $stmt->bind_param("ii",$limit,$offset);
}

$stmt->execute();
$result = $stmt->get_result();
$customers = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Customers — ASOVERIFY Admin</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body{background:#0b1d3a;color:#fff;font-family:Arial;padding:20px}
h2{color:#00d5ff}
.box{background:#122a52;padding:15px;border-radius:10px;margin-bottom:15px}
table{width:100%;border-collapse:collapse}
th,td{padding:10px;border-bottom:1px solid #1e3c72}
th{background:#0f2f66}
input,button{padding:8px;border-radius:6px;border:none}
button{background:#00d5ff;font-weight:bold}
a{color:#00d5ff;text-decoration:none}
.pagination a{margin:4px;padding:6px 10px;background:#1e3c72;border-radius:5px}
.pagination .active{background:#00d5ff;color:#000}
</style>
</head>

<body>

<h2>Customers Management</h2>

<!-- ADD CUSTOMER -->
<div class="box">
<h3>Add Customer</h3>
<form method="post">
<input name="full_name" placeholder="Full Name" required>
<input name="phone" placeholder="Phone" required>
<input name="email" placeholder="Email" required>
<input name="password" placeholder="Password" required>
<button name="add_customer">Add Customer</button>
</form>
</div>

<div class="box">
<form method="get">
<input name="search" placeholder="Search name / phone / email" value="<?= htmlspecialchars($search) ?>">
<button>Search</button>
<a href="users.php?export=csv" style="margin-left:10px">Export CSV</a>
</form>
</div>

<div class="box">
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Phone</th>
<th>Email</th>
<th>Password</th>
<th>Balance</th>
<th>Actions</th>
</tr>

<?php if(!$customers): ?>
<tr><td colspan="7">No customers found</td></tr>
<?php endif; ?>

<?php foreach($customers as $c): ?>
<tr>
<td><?= $c['id'] ?></td>
<td><?= htmlspecialchars($c['full_name']) ?></td>
<td><?= htmlspecialchars($c['phone']) ?></td>
<td><?= htmlspecialchars($c['email']) ?></td>
<td><?= htmlspecialchars($c['password']) ?></td>
<td>₦<?= number_format($c['balance'],2) ?></td>
<td>
<form method="post" style="display:inline">
<input type="hidden" name="deactivate_id" value="<?= $c['id'] ?>">
<button onclick="return confirm('Deactivate this customer?')">Deactivate</button>
</form>

<form method="post" style="display:inline">
<input type="hidden" name="user_id" value="<?= $c['id'] ?>">
<input type="number" step="0.01" name="amount" placeholder="₦">
<button name="fund_user">Fund</button>
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
</div>

<div class="pagination">
<?php for($i=1;$i<=$totalPages;$i++): ?>
<a class="<?= $i==$page?'active':'' ?>" href="?page=<?= $i ?>&search=<?= urlencode($search) ?>"><?= $i ?></a>
<?php endfor; ?>
</div>

</body>
</html>