<?php

require_once '../../core/api_bootstrap.php';
require_once '../../core/provider_auth.php';

$provider_id = ProviderAuth::id();

$data = Request::get();

try {

    $db = new Database();
    $conn = $db->connect();

    /*
    Pagination
    */

    $page = isset($data['page']) ? (int) $data['page'] : 1;
    $limit = isset($data['limit']) ? (int) $data['limit'] : 10;

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

    /*
    Filters
    */

    $where = "WHERE ld.provider_id = :provider";

    $params = [
        ':provider' => $provider_id
    ];

    /*
    Status filter
    */

    if (!empty($data['status'])) {

        $where .= " AND ld.status = :status";

        $params[':status'] = $data['status'];

    }

    /*
    Date filter
    */

    if (!empty($data['date'])) {

        $where .= " AND DATE(ld.sent_at) = :date";

        $params[':date'] = $data['date'];

    }

    /*
    Search filter
    */

    if (!empty($data['search'])) {

        $where .= " AND (l.name LIKE :search OR l.phone LIKE :search)";

        $params[':search'] = "%" . $data['search'] . "%";

    }

    /*
    Total leads
    */

    $countQuery = "

SELECT COUNT(*)

FROM leads_distribution ld

JOIN customer_leads l
ON ld.lead_id = l.id

$where

";

    $stmt = $conn->prepare($countQuery);
    $stmt->execute($params);

    $total = $stmt->fetchColumn();

    /*
    Lead list query
    */

    $query = "

SELECT

ld.id AS distribution_id,
l.id AS lead_id,
l.name,
l.phone,
l.address,
l.pincode,
c.name AS category,
sc.name AS sub_category,
ld.status,
ld.sent_at

FROM leads_distribution ld

JOIN customer_leads l
ON ld.lead_id = l.id

LEFT JOIN categories c
ON l.category_id = c.id

LEFT JOIN sub_categories sc
ON l.sub_category_id = sc.id

$where

ORDER BY ld.sent_at DESC

LIMIT $limit OFFSET $offset

";

    $stmt = $conn->prepare($query);
    $stmt->execute($params);

    $leads = $stmt->fetchAll();

    Response::success([

        "page" => $page,
        "limit" => $limit,
        "total" => (int) $total,
        "pages" => ceil($total / $limit),
        "data" => $leads

    ]);

} catch (Exception $e) {

    Logger::log("system.log", $e->getMessage());

    Response::error("Server error", 500);

}