<?php

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

EmployeeAuth::check('edit_leads');

require_once '../../core/whatsapp.php';
require_once '../../core/email.php';
require_once '../../modules/emails/provider-lead.php';

$data = Request::post();

try {

    Validator::required($data, ['lead_id']);

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


    /*
    GET LEAD
    */

    $stmt = $conn->prepare("
SELECT *
FROM customer_leads
WHERE id=:id
LIMIT 1
");

    $stmt->execute([
        ':id' => $data['lead_id']
    ]);

    $lead = $stmt->fetch();

    if (!$lead) {
        Response::error("Lead not found", 404);
    }


    /*
    GET PINCODE ID
    */

    $stmt = $conn->prepare("
SELECT id
FROM pincodes
WHERE pincode=:pincode
LIMIT 1
");

    $stmt->execute([
        ':pincode' => $lead['pincode']
    ]);

    $pincode = $stmt->fetch();

    if (!$pincode) {
        Response::error("Invalid pincode");
    }


    /*
    FIND ELIGIBLE PROVIDERS
    */

    $query = "

SELECT DISTINCT p.id,p.name,p.phone,p.email

FROM providers p

JOIN provider_service_area_map psam
ON p.id = psam.provider_id

JOIN provider_subscriptions ps
ON p.id = ps.provider_id

LEFT JOIN provider_lead_usage plu
ON p.id = plu.provider_id
AND plu.usage_date = CURDATE()

WHERE

p.account_status='active'
AND p.kyc_status='approved'

AND psam.sub_category_id=:subcategory
AND psam.pincode_id=:pincode

AND ps.status='active'
AND ps.expiry_date>=CURDATE()

AND (
plu.leads_received IS NULL
OR plu.leads_received < ps.daily_lead_limit
)

";

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

    $stmt->execute([

        ':subcategory' => $lead['sub_category_id'],
        ':pincode' => $pincode['id']

    ]);

    $providers = $stmt->fetchAll();


    $sent = 0;


    /*
    DISTRIBUTE LEAD
    */

    foreach ($providers as $provider) {

        /* prevent duplicate */

        $check = $conn->prepare("
SELECT id
FROM leads_distribution
WHERE lead_id=:lead
AND provider_id=:provider
");

        $check->execute([
            ':lead' => $lead['id'],
            ':provider' => $provider['id']
        ]);

        if ($check->fetch()) {
            continue;
        }


        /*
        SAVE DISTRIBUTION
        */

        $conn->prepare("

INSERT INTO leads_distribution
(lead_id,provider_id)

VALUES
(:lead,:provider)

")->execute([

                    ':lead' => $lead['id'],
                    ':provider' => $provider['id']

                ]);


        /*
        UPDATE DAILY LEAD USAGE
        */

        $conn->prepare("

INSERT INTO provider_lead_usage
(provider_id,usage_date,leads_received)

VALUES
(:provider,CURDATE(),1)

ON DUPLICATE KEY UPDATE
leads_received = leads_received + 1

")->execute([

                    ':provider' => $provider['id']

                ]);


        /*
        SEND WHATSAPP
        */

        $message = "

New Lead Received

Service: " . $lead['service'] . "
Customer: " . $lead['name'] . "
Phone: " . $lead['phone'] . "
Pincode: " . $lead['pincode'] . "

";

        WhatsApp::send($provider['phone'], $message);


        /*
        SEND EMAIL
        */

       // ProviderLeadEmail::send($provider, $lead);


        $sent++;

    }


    Response::success([
        "providers_sent" => $sent
    ]);

} catch (Exception $e) {

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

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

}