<?php
session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: /beauty_pos/login.php");
    exit;
}

include_once __DIR__ . "/../config/database.php";

$search = "";
$where = "";

if (isset($_GET['search'])) {
    $search = trim(mysqli_real_escape_string($conn, $_GET['search']));

    if ($search != "") {
        $where = " WHERE customer_name LIKE '%$search%'
                    OR phone LIKE '%$search%'
                    OR email LIKE '%$search%'";
    }
}

$limit = 10;

$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;

if ($page <= 0) {
    $page = 1;
}

$offset = ($page - 1) * $limit;

$totalQuery = mysqli_query(
    $conn,
    "SELECT COUNT(*) AS total
     FROM customers
     $where"
);

$totalRow = mysqli_fetch_assoc($totalQuery);

$totalRecords = (int)$totalRow['total'];

$totalPages = ceil($totalRecords / $limit);

$totalCustomers = 0;
$totalPoints = 0;
$totalBalance = 0;

$summary = mysqli_query(
    $conn,
    "SELECT
        COUNT(*) AS total_customers,
        IFNULL(SUM(loyalty_points),0) AS total_points,
        IFNULL(SUM(balance),0) AS total_balance
     FROM customers"
);

if ($summary && mysqli_num_rows($summary) > 0) {

    $sum = mysqli_fetch_assoc($summary);

    $totalCustomers = $sum['total_customers'];
    $totalPoints = $sum['total_points'];
    $totalBalance = $sum['total_balance'];
}

$query = mysqli_query(
    $conn,
    "SELECT *
     FROM customers
     $where
     ORDER BY id DESC
     LIMIT $offset,$limit"
);

include_once __DIR__ . "/../includes/header.php";
include_once __DIR__ . "/../includes/sidebar.php";
?>

<div class="overlay" id="overlay"></div>

<div class="main-content">

<?php include_once __DIR__ . "/../includes/topbar.php"; ?>

<div class="container-fluid py-4">

    <div class="d-flex flex-wrap justify-content-between align-items-center mb-4">

        <div>
            <h3 class="fw-bold mb-1">Customers</h3>
            <p class="text-muted mb-0">
                Manage customer records
            </p>
        </div>

        <a href="/beauty_pos/customers/add.php"
           class="btn btn-primary rounded-pill px-4">
            <i class="fa fa-plus me-2"></i>
            Add Customer
        </a>

    </div>

    <?php if(isset($_SESSION['success'])){ ?>

        <div class="alert alert-success alert-dismissible fade show">

            <?php
            echo $_SESSION['success'];
            unset($_SESSION['success']);
            ?>

            <button
                class="btn-close"
                data-bs-dismiss="alert">
            </button>

        </div>

    <?php } ?>

    <?php if(isset($_SESSION['error'])){ ?>

        <div class="alert alert-danger alert-dismissible fade show">

            <?php
            echo $_SESSION['error'];
            unset($_SESSION['error']);
            ?>

            <button
                class="btn-close"
                data-bs-dismiss="alert">
            </button>

        </div>

    <?php } ?>

    <div class="row g-4 mb-4">

        <div class="col-xl-4 col-lg-4 col-md-6 col-12">

            <div class="card rounded-4 shadow-sm border-0 h-100">

                <div class="card-body">

                    <small class="text-uppercase text-muted fw-semibold">
                        Total Customers
                    </small>

                    <h2 class="fw-bold mt-2 mb-0">

                        <?php echo $totalCustomers; ?>

                    </h2>

                </div>

            </div>

        </div>

        <div class="col-xl-4 col-lg-4 col-md-6 col-12">

            <div class="card rounded-4 shadow-sm border-0 h-100">

                <div class="card-body">

                    <small class="text-uppercase text-muted fw-semibold">
                        Loyalty Points
                    </small>

                    <h2 class="fw-bold mt-2 mb-0">

                        <?php echo number_format($totalPoints); ?>

                    </h2>

                </div>

            </div>

        </div>

        <div class="col-xl-4 col-lg-4 col-md-12 col-12">

            <div class="card rounded-4 shadow-sm border-0 h-100">

                <div class="card-body">

                    <small class="text-uppercase text-muted fw-semibold">
                        Store Credit
                    </small>

                    <h2 class="fw-bold mt-2 mb-0">

                        ₹<?php echo number_format($totalBalance,2); ?>

                    </h2>

                </div>

            </div>

        </div>

    </div>

    <div class="card rounded-4 shadow-sm border-0">

        <div class="card-body">

            <form method="GET">

                <div class="row g-3 align-items-end">

                    <div class="col-lg-5 col-md-8 col-12">

                        <label class="form-label">
                            Search Customer
                        </label>

                        <input
                            type="text"
                            class="form-control"
                            name="search"
                            value="<?php echo htmlspecialchars($search); ?>"
                            placeholder="Name / Phone / Email">

                    </div>

                    <div class="col-lg-2 col-md-4 col-6">

                        <button
                            class="btn btn-primary w-100"
                            type="submit">

                            Search

                        </button>

                    </div>

                    <div class="col-lg-2 col-md-4 col-6">

                        <a
                           href="/beauty_pos/customers/index.php"
                           class="btn btn-secondary w-100">

                            Reset

                        </a>

                    </div>

                </div>

            </form>

        </div>

    </div>

    <div class="card rounded-4 shadow-sm border-0 mt-4">

        <div class="card-body">

            <div class="table-responsive">

                <table class="table align-middle table-hover">

                    <thead>

                    <tr>

                        <th>#</th>

                        <th>Name</th>

                        <th>Phone</th>

                        <th>Email</th>

                        <th>Points</th>

                        <th>Balance</th>

                        <th>Created</th>

                        <th width="170">
                            Action
                        </th>

                    </tr>

                    </thead>

                    <tbody>
                        <?php

if(mysqli_num_rows($query)>0){

$sr = $offset + 1;

while($row=mysqli_fetch_assoc($query)){

?>

<tr>

    <td>
        <?php echo $sr++; ?>
    </td>

    <td>

        <div class="fw-semibold">

            <?php echo htmlspecialchars($row['customer_name']); ?>

        </div>

        <?php

        if(!empty($row['address'])){

        ?>

        <small class="text-muted">

            <?php

            echo nl2br(htmlspecialchars($row['address']));

            ?>

        </small>

        <?php } ?>

    </td>

    <td>

        <?php

        echo !empty($row['phone'])
            ? htmlspecialchars($row['phone'])
            : "-";

        ?>

    </td>

    <td>

        <?php

        echo !empty($row['email'])
            ? htmlspecialchars($row['email'])
            : "-";

        ?>

    </td>

    <td>

        <span class="badge bg-warning text-dark px-3 py-2">

            <?php

            echo number_format($row['loyalty_points']);

            ?>

        </span>

    </td>

    <td>

        <?php

        if($row['balance']>0){

        ?>

        <span class="badge bg-success px-3 py-2">

            ₹<?php echo number_format($row['balance'],2); ?>

        </span>

        <?php

        }else{

            echo "-";

        }

        ?>

    </td>

    <td>

        <?php

        echo date(
            "d M Y",
            strtotime($row['created_at'])
        );

        ?>

    </td>

    <td>

        <div class="d-flex gap-2">

            <a href="/beauty_pos/customers/edit.php?id=<?php echo $row['id']; ?>"
               class="btn btn-sm btn-primary">

                <i class="fa fa-pen"></i>

            </a>

            <a href="/beauty_pos/customers/delete.php?id=<?php echo $row['id']; ?>"
               class="btn btn-sm btn-danger"
               onclick="return confirm('Delete this customer?');">

                <i class="fa fa-trash"></i>

            </a>

        </div>

    </td>

</tr>

<?php

}

}else{

?>

<tr>

    <td colspan="8" class="text-center py-5">

        No Customer Found.

    </td>

</tr>

<?php

}

?>

</tbody>

</table>

</div>

<?php

if($totalPages>1){

?>

<nav class="mt-4">

<ul class="pagination justify-content-end flex-wrap">

<?php

if($page>1){

?>

<li class="page-item">

<a class="page-link"

href="?search=<?php echo urlencode($search); ?>&page=<?php echo $page-1; ?>">

Previous

</a>

</li>

<?php

}

for($i=1;$i<=$totalPages;$i++){

?>

<li class="page-item <?php if($page==$i) echo 'active'; ?>">

<a class="page-link"

href="?search=<?php echo urlencode($search); ?>&page=<?php echo $i; ?>">

<?php echo $i; ?>

</a>

</li>

<?php

}

if($page<$totalPages){

?>

<li class="page-item">

<a class="page-link"

href="?search=<?php echo urlencode($search); ?>&page=<?php echo $page+1; ?>">

Next

</a>

</li>

<?php

}

?>

</ul>

</nav>

<?php

}

?>

</div>

</div>

</div>

<?php

include_once __DIR__."/../includes/footer.php";

?>