<?php

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

$provider = $_SESSION['provider'];
$provider_id = $provider['id'];

$subscriptionName = "Free Plan";
$todayLeads = 0;
$totalCategories = 0;
$totalLeads = 0;
$todayLeadList = [];
$leadLimit = 0;
$expiryDate = null;


/*
------------------------------------
FULL PROFILE API
------------------------------------
*/

$profileUrl = API_URL . "providers/full-profile.php?provider_id=" . $provider_id;

$ch = curl_init();

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

$profileResponse = curl_exec($ch);

if (!curl_errno($ch)) {

    $profileData = json_decode($profileResponse, true);

    if (isset($profileData['data'])) {

        $subscriptionName = $profileData['data']['subscription']['plan_name'] ?? "Free Plan";

        $todayLeads = $profileData['data']['today_leads'] ?? 0;

        $leadLimit = $profileData['data']['subscription']['daily_lead_limit'] ?? 0;

        $expiryDate = $profileData['data']['subscription']['expiry_date'] ?? null;

        $totalCategories = isset($profileData['data']['services'])
            ? count($profileData['data']['services'])
            : 0;

    }

}

curl_close($ch);


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

$leadsUrl = API_URL . "providers/leads.php?page=1&limit=10";

$ch = curl_init();

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

$leadResponse = curl_exec($ch);

if (!curl_errno($ch)) {

    $leadData = json_decode($leadResponse, true);

    if (isset($leadData['data'])) {

        $totalLeads = $leadData['data']['total'] ?? 0;
        $todayLeadList = $leadData['data']['data'] ?? [];

    }

}

curl_close($ch);


/*
------------------------------------
LEAD PROGRESS CALCULATION
------------------------------------
*/

$remainingLeads = max(0, $leadLimit - $todayLeads);

$leadPercent = ($leadLimit > 0)
    ? ($todayLeads / $leadLimit) * 100
    : 0;


include '../admin/partials/layouts/layoutTop.php';

?>


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


    <!-- HEADER -->

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

        <h6 class="fw-semibold mb-0">Provider Dashboard</h6>

    </div>



    <!-- ACTIVE PLAN BANNER -->

    <div class="card mb-24 border-success">

        <div class="card-body p-20">

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

                <div>

                    <h5 class="text-success mb-2">

                        Active Plan: <?php echo htmlspecialchars($subscriptionName); ?>

                    </h5>

                    <?php if ($expiryDate): ?>

                        <span class="text-secondary-light">

                            Valid until

                            <strong>

                                <?php echo date("d M Y", strtotime($expiryDate)); ?>

                            </strong>

                        </span>

                    <?php endif; ?>

                </div>

                <a href="subscription.php" class="btn btn-primary radius-8">

                    Manage Subscription

                </a>

            </div>

        </div>

    </div>



    <!-- DASHBOARD STATS -->

    <div class="row gy-4">

        <div class="col-xl-3 col-md-6">

            <div class="shadow-7 p-20 radius-12 bg-base">

                <span class="text-neutral-800">Total Leads</span>

                <h5 class="mt-2 mb-0">

                    <?php echo $totalLeads; ?>

                </h5>

            </div>

        </div>


        <div class="col-xl-3 col-md-6">

            <div class="shadow-7 p-20 radius-12 bg-base">

                <span class="text-neutral-800">Service Categories</span>

                <h5 class="mt-2 mb-0">

                    <?php echo $totalCategories; ?>

                </h5>

            </div>

        </div>


        <div class="col-xl-3 col-md-6">

            <div class="shadow-7 p-20 radius-12 bg-base">

                <span class="text-neutral-800">Today's Leads</span>

                <h5 class="mt-2 mb-0">

                    <?php echo $todayLeads; ?>

                </h5>

            </div>

        </div>


        <div class="col-xl-3 col-md-6">

            <div class="shadow-7 p-20 radius-12 bg-base">

                <span class="text-neutral-800">Remaining Leads</span>

                <h5 class="mt-2 mb-0">

                    <?php echo $remainingLeads; ?>

                </h5>

            </div>

        </div>

    </div>



    <!-- LEAD USAGE BAR -->

    <?php if ($leadLimit > 0): ?>

        <div class="card mt-24">

            <div class="card-body p-20">

                <h6 class="mb-16">Daily Lead Usage</h6>

                <div class="mb-6">

                    <?php echo $todayLeads ?> of <?php echo $leadLimit ?> leads used

                </div>

                <div class="progress" style="height:8px">

                    <div class="progress-bar bg-primary" style="width:<?php echo $leadPercent ?>%">

                    </div>

                </div>

                <small class="text-secondary-light">

                    <?php echo $remainingLeads ?> leads remaining today

                </small>

            </div>

        </div>

    <?php endif; ?>



    <!-- RECENT LEADS -->

    <div class="card radius-12 mt-24">

        <div class="card-header border-bottom">

            <h6 class="mb-0 fw-bold">Recent Leads</h6>

        </div>

        <div class="card-body p-0">

            <div class="table-responsive">

                <table class="table bordered-table mb-0">

                    <thead>

                        <tr>

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

                        </tr>

                    </thead>

                    <tbody>

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

                            <?php foreach ($todayLeadList 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 isset($lead['sent_at'])
                                            ? date("d M Y H:i", strtotime($lead['sent_at']))
                                            : '-';

                                        ?>

                                    </td>

                                </tr>

                            <?php endforeach; ?>

                        <?php else: ?>

                            <tr>

                                <td colspan="7" class="text-center py-20">

                                    No Leads Found

                                </td>

                            </tr>

                        <?php endif; ?>

                    </tbody>

                </table>

            </div>

        </div>

    </div>


</div>


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