<?php
session_start();
require_once '../config/database.php';

if (!isset($_SESSION["user_id"]) || $_SESSION["role"] !== "admin") {
    header("Location: ../auth/login.php");
    exit;
}

$message = "";
$error = "";

if (isset($_GET["delete"])) {
    $customer_id = intval($_GET["delete"]);

    $stmt = $pdo->prepare("SELECT user_id FROM customers WHERE id = ?");
    $stmt->execute([$customer_id]);
    $customer = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($customer) {
        $pdo->beginTransaction();

        $stmt = $pdo->prepare("DELETE FROM customers WHERE id = ?");
        $stmt->execute([$customer_id]);

        if (!empty($customer["user_id"])) {
            $stmt = $pdo->prepare("DELETE FROM users WHERE id = ? AND role = 'customer'");
            $stmt->execute([$customer["user_id"]]);
        }

        $pdo->commit();
        $message = "Customer deleted successfully.";
    }
}

if (isset($_GET["reset"])) {
    $customer_id = intval($_GET["reset"]);
    $new_password = "customer123";
    $hash = password_hash($new_password, PASSWORD_DEFAULT);

    $stmt = $pdo->prepare("
        UPDATE users u
        JOIN customers c ON c.user_id = u.id
        SET u.password = ?
        WHERE c.id = ? AND u.role = 'customer'
    ");
    $stmt->execute([$hash, $customer_id]);

    $message = "Password reset successfully. New password: customer123";
}

$search = isset($_GET["search"]) ? trim($_GET["search"]) : "";

if ($search !== "") {
    $stmt = $pdo->prepare("
        SELECT c.*, u.email AS login_email
        FROM customers c
        LEFT JOIN users u ON c.user_id = u.id
        WHERE c.full_name LIKE ?
           OR c.phone LIKE ?
           OR c.email LIKE ?
           OR c.customer_code LIKE ?
        ORDER BY c.id DESC
    ");
    $like = "%" . $search . "%";
    $stmt->execute([$like, $like, $like, $like]);
} else {
    $stmt = $pdo->query("
        SELECT c.*, u.email AS login_email
        FROM customers c
        LEFT JOIN users u ON c.user_id = u.id
        ORDER BY c.id DESC
    ");
}

$customers = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Customers - Admin</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f4f6f8;
            margin: 0;
            padding: 30px;
        }

        .container {
            max-width: 1200px;
            margin: auto;
        }

        .card {
            background: white;
            border-radius: 12px;
            padding: 24px;
            box-shadow: 0 4px 14px rgba(0,0,0,0.08);
        }

        h1 {
            margin-top: 0;
        }

        .top-bar {
            display: flex;
            justify-content: space-between;
            gap: 12px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        input[type="text"] {
            padding: 10px;
            width: 280px;
            border: 1px solid #ccc;
            border-radius: 8px;
        }

        button, .btn {
            padding: 10px 14px;
            border: none;
            border-radius: 8px;
            text-decoration: none;
            cursor: pointer;
            display: inline-block;
            font-size: 14px;
        }

        .btn-primary {
            background: #2563eb;
            color: white;
        }

        .btn-edit {
            background: #16a34a;
            color: white;
        }

        .btn-reset {
            background: #f59e0b;
            color: white;
        }

        .btn-delete {
            background: #dc2626;
            color: white;
        }

        .btn-gray {
            background: #6b7280;
            color: white;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background: white;
        }

        th {
            background: #111827;
            color: white;
            text-align: left;
            padding: 12px;
        }

        td {
            padding: 12px;
            border-bottom: 1px solid #e5e7eb;
        }

        tr:hover {
            background: #f9fafb;
        }

        .success {
            color: #15803d;
            background: #dcfce7;
            padding: 10px;
            border-radius: 8px;
        }

        .error {
            color: #b91c1c;
            background: #fee2e2;
            padding: 10px;
            border-radius: 8px;
        }

        .balance {
            font-weight: bold;
            color: #2563eb;
        }

        .actions a {
            margin-right: 6px;
            margin-bottom: 6px;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="card">
        <h1>Customers</h1>

        <?php if ($message): ?>
            <p class="success"><?php echo htmlspecialchars($message); ?></p>
        <?php endif; ?>

        <?php if ($error): ?>
            <p class="error"><?php echo htmlspecialchars($error); ?></p>
        <?php endif; ?>

        <div class="top-bar">
            <form method="GET">
                <input type="text" name="search" placeholder="Search customer..." value="<?php echo htmlspecialchars($search); ?>">
                <button class="btn btn-primary" type="submit">Search</button>
                <a class="btn btn-gray" href="customers.php">Clear</a>
            </form>

            <a class="btn btn-primary" href="create_customer.php">+ Create Customer</a>
        </div>

        <table>
            <tr>
                <th>ID</th>
                <th>Customer Code</th>
                <th>Name</th>
                <th>Phone</th>
                <th>Email</th>
                <th>Balance</th>
                <th>Status</th>
                <th>Actions</th>
            </tr>

            <?php foreach ($customers as $customer): ?>
                <tr>
                    <td><?php echo $customer["id"]; ?></td>
                    <td><?php echo htmlspecialchars($customer["customer_code"]); ?></td>
                    <td><?php echo htmlspecialchars($customer["full_name"]); ?></td>
                    <td><?php echo htmlspecialchars($customer["phone"]); ?></td>
                    <td><?php echo htmlspecialchars($customer["email"]); ?></td>
                    <td class="balance"><?php echo number_format($customer["balance"], 2); ?></td>
                    <td><?php echo htmlspecialchars($customer["status"]); ?></td>
                    <td class="actions">
                        <a class="btn btn-edit" href="edit_customer.php?id=<?php echo $customer["id"]; ?>">Edit</a>
                        <a class="btn btn-reset" href="customers.php?reset=<?php echo $customer["id"]; ?>" onclick="return confirm('Reset password to customer123?');">Reset Password</a>
                        <a class="btn btn-delete" href="customers.php?delete=<?php echo $customer["id"]; ?>" onclick="return confirm('Delete this customer?');">Delete</a>
                    </td>
                </tr>
            <?php endforeach; ?>
        </table>

        <br>
        <a class="btn btn-gray" href="dashboard.php">Back to Dashboard</a>
    </div>
</div>

</body>
</html>