<?php
// Simple script to log incoming requests
require_once(__DIR__ . '/crest.php');
//require_once('../surepassApis.php');
require_once(__DIR__ . '/surepassApis.php');

try {
    if (isset($_REQUEST['PLACEMENT_OPTIONS'])) {
        $dealPlacement = json_decode($_REQUEST['PLACEMENT_OPTIONS'], true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception("Error decoding PLACEMENT_OPTIONS: " . json_last_error_msg());
        }
        $dealId = $dealPlacement['ID'];
    } else {
        throw new Exception("PLACEMENT_OPTIONS not found in the request.");
    }

    $response = checkExistingApiData($dealId);
    echo "<pre>";
    //print_r($response);
    echo "</pre>";
    if(isset($response['message'])){
    	echo '<p class="redclr">'.$response['message'].'</p>';
    }
    
    

} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}


function checkExistingApiData($dealId)
{
    try {
        $deal = getDeal($dealId);
        $vehicleNumber = $deal['UF_CRM_657A8556EA17C'];
        if (empty($vehicleNumber)) {
            throw new Exception("Vehicle number not found in the deal.");
        }
        
        $fields = ['ID', 'STAGE_ID', 'UF_CRM_657A8556EA17C', 'UF_CRM_1722269383', 'UF_CRM_1689412695', 'UF_CRM_1707034449', 'UF_CRM_1722269439',
            'UF_CRM_1722757025397', 'UF_CRM_1722763762758', 'UF_CRM_1722269536', 'UF_CRM_1721409291383', 'UF_CRM_1721409255084', 'UF_CRM_6503E06165ABF',
            'UF_CRM_1722269585', 'UF_CRM_1722927145947', 'UF_CRM_1722269718', 'UF_CRM_1721409885267', 'UF_CRM_1722862270631', 'UF_CRM_1693205894',
            'UF_CRM_64E72F2857676', 'UF_CRM_1722269775', 'UF_CRM_1722269847', 'UF_CRM_1689414361007', 'UF_CRM_1722270007', 'UF_CRM_1722270049',
            'UF_CRM_1722270087', 'UF_CRM_1722270133', 'UF_CRM_1722269929'];

       
         // Check if the stage ID is C9:1(Lead from last year lost)
        if ($deal['STAGE_ID'] == "C9:1") {
            echo "<button id='apiData' class='updateBtn'>Update Vahan Information</button>";
            return rcFull($vehicleNumber);
        }
         // Check if the RC number already exists in other deals
        $existingDeals = CRest::call('crm.deal.list', [
            'filter' => ['UF_CRM_657A8556EA17C' => $vehicleNumber],
            'select' => $fields,
            'order' => ['ID' => 'DESC']
        ]);

        if (empty($existingDeals['result'])) {
            throw new Exception("No existing deals found.");
        }

        foreach ($existingDeals['result'] as $existingDeal) {
            // Check if the existing deal has the required data
            if (!empty($existingDeal['UF_CRM_1721409291383'])) {
                echo "<button id='dealData' class='updateBtn'>Update Vahan Info</button>";
                return $existingDeal;
            }
        }

        // If none of the existing deals have the required data, call the API
        
            
          echo "<button id='apiData' class='updateBtn'>Update Vahan Information</button>";
          return rcFull($vehicleNumber);
        

    } catch (Exception $e) {
        echo "Error: " . $e->getMessage();
    }
}








function getDeal($dealId)
{
    try {
        $fields = ['ID', 'STAGE_ID', 'UF_CRM_657A8556EA17C', 'UF_CRM_1722269383', 'UF_CRM_1689412695', 'UF_CRM_1707034449', 'UF_CRM_1722269439',
            'UF_CRM_1722757025397', 'UF_CRM_1722763762758', 'UF_CRM_1722269536', 'UF_CRM_1721409291383', 'UF_CRM_1721409255084', 'UF_CRM_6503E06165ABF',
            'UF_CRM_1722269585', 'UF_CRM_1722927145947', 'UF_CRM_1722269718', 'UF_CRM_1721409885267', 'UF_CRM_1722862270631', 'UF_CRM_1693205894',
            'UF_CRM_64E72F2857676', 'UF_CRM_1722269775', 'UF_CRM_1722269847', 'UF_CRM_1689414361007', 'UF_CRM_1722270007', 'UF_CRM_1722270049',
            'UF_CRM_1722270087', 'UF_CRM_1722270133', 'UF_CRM_1722269929'];
        $result = CRest::call('crm.deal.list', [
            'filter' => ['ID' => $dealId],
            'select' => $fields
        ]);
        if (empty($result['result'])) {
            throw new Exception("Deal not found.");
        }
        return $result['result'][0];
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vahan Information</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .updateBtn {
            padding: 20px;
            border-radius: 25px;
            background-color: green;
            color: white;
            display: flex;
            justify-content: flex-end;
            margin-left: auto;
            margin-bottom: 20px;
            margin-top: 20px;
        }
        .redclr{
        	color:red;
        }
    </style>
</head>
<body>
    <script>
        $(document).ready(function() {
            var response = <?php echo json_encode($response); ?>;
            var dealId = <?php echo json_encode($dealId); ?>;
            $('#apiData').click(function() {
                $.ajax({
                    url: 'updateDeal.php',
                    type: 'POST',
                    data: { action: 'getApiData', dealId: dealId, rcNumber: 'UK01B4843', response: JSON.stringify(response) },
                    success: function(response) {
                        console.log(response);
                        alert('Response: ' + response);
                    },
                    error: function(xhr, status, error) {
                        alert('Error: ' + error);
                    }
                });
            });
            $('#dealData').click(function() {
                $.ajax({
                    url: 'updateDeal.php',
                    type: 'POST',
                    data: { action: 'getDealData', dealId: dealId, rcNumber: 'UK01B4843', response: JSON.stringify(response) },
                    success: function(response) {
                        console.log(response);
                        alert('Response: ' + response);
                    },
                    error: function(xhr, status, error) {
                        alert('Error: ' + error);
                    }
                });
            });
        });
    </script>
</body>
</html>

<table border>
    <thead>
        <th>RC NUMBER</th>
        <th>FIT UP TO</th>
        <th>REGISTRATION DATE</th>
        <th>OWNER NAME</th>
        <th>FATHER NAME</th>
        <th>PRESENT ADDRESS</th>
        <th>MOBILE NUMBER</th>
        <th>VEHICLE CATEGORY</th>
        <th>VEHICLE CHASI NUMBER</th>
        <th>VEHICLE ENGINE NUMBER</th>
        <th>MAKER MODEL</th>
        <th>BODY TYPE</th>
        <th>FUEL TYPE</th>
        <th>COLOR</th>
        <th>FINANCER</th>
        <th>INSURANCE COMPANY</th>
        <th>INSURANCE POLICY NUMBER</th>
        <th>INSURANCE UPTO</th>
        <th>MANUFACTURING DATE</th>
        <th>REGISTERED AT</th>
        <th>LATEST BY</th>
        <th>CUBIC CAPACITY</th>
        <th>VEHICLE GROSS WEIGHT</th>
        <th>SEAT CAPACITY</th>
        <th>PUCC NUMBER</th>
        <th>PUCC UPTO</th>
    </thead>
   	<tbody>
    <?php if (isset($response['data']['rc_number']) || isset($response['UF_CRM_657A8556EA17C'])) { ?>
        <?php if (isset($response['data']['rc_number'])) { ?>
            <tr>
                <td><?= htmlspecialchars($response['data']['rc_number'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['data']['fit_up_to'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['data']['registration_date'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['data']['owner_name'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['data']['father_name'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['data']['present_address'] ?? '') ?></td>
                <td>Mobile Number</td>
                <td><?= htmlspecialchars($response['data']['vehicle_category'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['data']['vehicle_chasi_number'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['data']['vehicle_engine_number'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['data']['maker_model'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['data']['body_type'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['data']['fuel_type'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['data']['color'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['data']['financer'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['data']['insurance_company'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['data']['insurance_policy_number'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['data']['insurance_upto'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['data']['manufacturing_date'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['data']['registered_at'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['data']['latest_by'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['data']['cubic_capacity'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['data']['vehicle_gross_weight'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['data']['seat_capacity'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['data']['pucc_number'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['data']['pucc_upto'] ?? '') ?></td>
            </tr>
        <?php } else { ?>
            <tr>
                <td><?= htmlspecialchars($response['UF_CRM_657A8556EA17C'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_1722269383'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_1689412695'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_1707034449'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_1722269439'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_1722757025397'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_1722763762758'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_1722269536'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_1721409291383'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_1721409255084'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_6503E06165ABF'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_1722269585'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_1722927145947'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_1722269718'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_1721409885267'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_1722862270631'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_1693205894'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_64E72F2857676'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_1722269775'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_1722269847'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_1722269929'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_1689414361007'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_1722270007'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_1722270049'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_1722270087'] ?? '') ?></td>
                <td><?= htmlspecialchars($response['UF_CRM_1722270133'] ?? '') ?></td>
            </tr>
        <?php } ?>
    <?php } else { ?>
        <tr>
            <td colspan="26">No data found</td>
        </tr>
    <?php } ?>
</tbody>

</table>