<?php

require_once 'includes/provider_auth.php';
require_once '../config/constants.php';

/*
-----------------------------------
DATE FILTER
-----------------------------------
*/

$start_date = $_GET['start_date'] ?? date('Y-m-01');
$end_date   = $_GET['end_date'] ?? date('Y-m-d');

/*
-----------------------------------
CALL LEADS API
-----------------------------------
*/

$api = API_URL . "providers/leads.php";

$ch = curl_init();

curl_setopt_array($ch, [
    CURLOPT_URL => $api,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'X-API-KEY: ' . API_KEY,
        'Authorization: Bearer ' . $_SESSION['provider_token']
    ]
]);

$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);

$leads = $data['data']['data'] ?? [];

/*
-----------------------------------
FILTER LEADS BY DATE
-----------------------------------
*/

$filtered_leads = [];

foreach ($leads as $lead) {

    $lead_date = date('Y-m-d', strtotime($lead['sent_at']));

    if ($lead_date >= $start_date && $lead_date <= $end_date) {
        $filtered_leads[] = $lead;
    }
}

?>

<?php include '../admin/partials/layouts/layoutTop.php' ?>


<div class="dashboard-main-body">

<div class="card">

<div class="card-body">

<h5 class="mb-4">Lead History</h5>

<!-- FILTER FORM -->

<form method="GET" class="row mb-4">

<div class="col-md-4">
<label>Start Date</label>
<input type="date" name="start_date"
value="<?php echo $start_date ?>"
class="form-control">
</div>

<div class="col-md-4">
<label>End Date</label>
<input type="date" name="end_date"
value="<?php echo $end_date ?>"
class="form-control">
</div>

<div class="col-md-4 d-flex align-items-end">

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

Filter Leads

</button>

</div>

</form>


<!-- LEADS TABLE -->

<div class="table-responsive">

<table class="table table-bordered">

<thead>

<tr>

<th>ID</th>
<th>Name</th>
<th>Phone</th>
<th>Category</th>
<th>Sub Category</th>
<th>Status</th>
<th>Lead Date</th>
<th>Action</th>

</tr>

</thead>

<tbody>

<?php if(!empty($filtered_leads)) : ?>

<?php foreach($filtered_leads as $lead) : ?>

<tr>

<td><?php echo $lead['lead_id'] ?></td>

<td><?php echo htmlspecialchars($lead['name']) ?></td>

<td><?php echo htmlspecialchars($lead['phone']) ?></td>

<td><?php echo htmlspecialchars($lead['category']) ?></td>

<td><?php echo htmlspecialchars($lead['sub_category']) ?></td>

<td><?php echo ucfirst($lead['status']) ?></td>

<td><?php echo date('d M Y H:i', strtotime($lead['sent_at'])) ?></td>

<td>

<a href="lead-view.php?id=<?php echo $lead['distribution_id'] ?>"
class="btn btn-sm btn-info">

View

</a>

</td>

</tr>

<?php endforeach; ?>

<?php else : ?>

<tr>
<td colspan="8" class="text-center">
No leads found
</td>
</tr>

<?php endif; ?>

</tbody>

</table>

</div>

</div>

</div>

</div>

<?php include '../admin/partials/layouts/layoutBottom.php' ?>