<?php
require_once "../config/auth.php";
require_once "../config/db.php";
require_once "../config/helpers.php";

$pageTitle = "Services";

require_once "../includes/header.php";
require_once "../includes/sidebar.php";
require_once "../includes/topbar.php";

// ================= INPUT =================
$month     = $_GET['month'] ?? '';
$year      = $_GET['year'] ?? '';
$customer  = $_GET['customer'] ?? '';
$type      = $_GET['type'] ?? '';
$sort      = $_GET['sort'] ?? 'renewal_date';
$page      = max(1, (int)($_GET['page'] ?? 1));
$limit     = 10;
$offset    = ($page - 1) * $limit;

// ================= WHERE =================
$where = [];

if($month){
    $where[] = "MONTH(s.renewal_date) = '$month'";
}
if($year){
    $where[] = "YEAR(s.renewal_date) = '$year'";
}
if($customer){
    $where[] = "s.customer_id = '$customer'";
}
if($type){
    $where[] = "s.type = '$type'";
}

$whereSQL = $where ? "WHERE " . implode(" AND ", $where) : "";

// ================= SORT =================
$allowedSort = ['customer','type','amount','renewal_date'];
if(!in_array($sort, $allowedSort)){
    $sort = 'renewal_date';
}

$orderBy = ($sort == 'customer') ? 'c.name' : "s.$sort";

// ================= COUNT =================
$totalRows = $conn->query("
SELECT COUNT(*) as total
FROM services s
JOIN customers c ON s.customer_id = c.id
$whereSQL
")->fetch_assoc()['total'];

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

// ================= DATA =================
$result = $conn->query("
SELECT s.*, c.name as customer_name
FROM services s
JOIN customers c ON s.customer_id = c.id
$whereSQL
ORDER BY $orderBy ASC
LIMIT $limit OFFSET $offset
");

// ================= CUSTOMERS =================
$customers = $conn->query("SELECT id,name FROM customers");
?>

<div class="main-content">
<div class="col-lg-12">

<div class="p-4">

<!-- HEADER -->
<div class="d-flex justify-content-between align-items-center mb-3">
    <h5>Services</h5>
    <a href="add_service.php" class="btn btn-primary">+ Add Service</a>
</div>

<!-- FILTER -->
<form method="GET" class="row g-2 mb-3">

<div class="col-md-2">
<input type="text" id="liveSearch" class="form-control" placeholder="Search...">
</div>

<div class="col-md-1">
<input type="number" name="month" class="form-control" placeholder="M" value="<?= $month ?>">
</div>

<div class="col-md-1">
<input type="number" name="year" class="form-control" placeholder="Y" value="<?= $year ?>">
</div>

<div class="col-md-2">
<select name="customer" class="form-control">
<option value="">Customer</option>
<?php while($c = $customers->fetch_assoc()){ ?>
<option value="<?= $c['id'] ?>" <?= ($customer==$c['id'])?'selected':'' ?>>
<?= e($c['name']) ?>
</option>
<?php } ?>
</select>
</div>

<div class="col-md-2">
<select name="type" class="form-control">
<option value="">Type</option>
<option value="domain" <?= ($type=='domain')?'selected':'' ?>>Domain</option>
<option value="hosting" <?= ($type=='hosting')?'selected':'' ?>>Hosting</option>
<option value="amc" <?= ($type=='amc')?'selected':'' ?>>AMC</option>
<option value="other" <?= ($type=='other')?'selected':'' ?>>Other</option>
</select>
</div>

<div class="col-md-2">
<select name="sort" class="form-control">
<option value="renewal_date">Sort Renewal</option>
<option value="amount" <?= ($sort=='amount')?'selected':'' ?>>Amount</option>
<option value="type" <?= ($sort=='type')?'selected':'' ?>>Type</option>
<option value="customer" <?= ($sort=='customer')?'selected':'' ?>>Customer</option>
</select>
</div>

<div class="col-md-2">
<button class="btn btn-primary w-100">Apply</button>
</div>

</form>

<!-- TABLE -->
<div class="table-responsive">
<table class="table table-bordered table-striped">

<thead class="table-dark">
<tr>
    <th>Customer</th>
    <th>Service</th>
    <th>Type</th>
    <th>Selling</th>
    <th>Cost</th>
    <th>Profit</th>
    <th>Renewal</th>
    <th>Action</th>
</tr>
</thead>

<tbody id="serviceTable">

<?php if($result->num_rows > 0){ ?>
<?php while($row = $result->fetch_assoc()){ 

$profit = $row['amount'] - $row['cost'];
?>

<tr>
    <td><?= e($row['customer_name']) ?></td>
    <td><?= e($row['service_name']) ?></td>
    <td><?= ucfirst($row['type']) ?></td>

    <!-- SELLING -->
    <td>₹<?= number_format($row['amount'],2) ?></td>

    <!-- COST -->
    <td>₹<?= number_format($row['cost'],2) ?></td>

    <!-- PROFIT -->
    <td>
        <?php if($profit >= 0){ ?>
            <span class="text-success fw-bold">
                ₹<?= number_format($profit,2) ?>
            </span>
        <?php } else { ?>
            <span class="text-danger fw-bold">
                ₹<?= number_format($profit,2) ?>
            </span>
        <?php } ?>
    </td>

    <!-- RENEWAL -->
    <td><?= date('d-m-Y', strtotime($row['renewal_date'])) ?></td>

    <!-- ACTION -->
    <td>
        <a href="../actions/edit_service.php?id=<?= $row['id'] ?>" class="btn btn-warning btn-sm">Edit</a>
        <a href="#"
   class="btn btn-danger btn-sm deleteBtn"
   data-id="<?= $row['id'] ?>"
   data-url="../actions/delete_service.php"
>
   Delete
</a>
    </td>
</tr>

<?php } ?>
<?php } else { ?>
<tr><td colspan="8" class="text-center">No data found</td></tr>
<?php } ?>

</tbody>
</table>
</div>

<!-- PAGINATION -->
<nav>
<ul class="pagination mt-3">
<?php for($i=1; $i <= $totalPages; $i++){ ?>
<li class="page-item <?= ($i==$page)?'active':'' ?>">
<a class="page-link" href="?<?= http_build_query(array_merge($_GET,['page'=>$i])) ?>">
<?= $i ?>
</a>
</li>
<?php } ?>
</ul>
</nav>

</div>
</div>
</div>

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