<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

include '../db_connect.php';

/* -------------------------------------------------
   FETCH EMPLOYEE DATA
------------------------------------------------- */

$sql = "

SELECT

    e.emp_code,
    e.name,
    e.mobile1,

    e.reporting_to_emp_code,
    e.reporting_to_name,
    e.reporting_to_mobile1,

    e.sales_off_desc,
    e.level,
    e.role_name,

    GROUP_CONCAT(
        DISTINCT m.website_id
        ORDER BY m.website_id ASC
        SEPARATOR ', '
    ) AS connected_websites,

    COUNT(DISTINCT m.website_id)
    AS total_dealers

FROM dealer_connected_employees e

LEFT JOIN dealer_employee_website_mapping m
    ON m.emp_code = e.emp_code

GROUP BY e.emp_code

ORDER BY
    CAST(e.level AS UNSIGNED) ASC,
    e.name ASC

";

$res = $conn->query($sql);

?>

<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="UTF-8">
<meta name="viewport"
      content="width=device-width, initial-scale=1">

<title>Employee Dealer Mapping</title>

<!-- Bootstrap -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
rel="stylesheet">

<!-- DataTables -->
<link
href="https://cdn.datatables.net/1.13.8/css/dataTables.bootstrap5.min.css"
rel="stylesheet">

<style>

body{
    background:#f5f7fb;
}

.page-title{
    font-size:28px;
    font-weight:700;
}

.table td{
    vertical-align:top;
}

.website-box{
    max-width:500px;
    white-space:normal;
    line-height:1.6;
}

.badge-level{
    font-size:12px;
}

.dataTables_filter{
    margin-bottom:15px;
}

</style>

</head>
<body>
					<div class="mb-3">

						<form method="post" action="?action=send_test" class="row g-2">

							<div class="col-md-4">
								<input
									type="text"
									name="test_name"
									class="form-control"
									placeholder="Enter Name"
									required>
							</div>

							<div class="col-md-4">
								<input
									type="text"
									name="test_mobile"
									class="form-control"
									placeholder="Enter 10 Digit Mobile Number"
									pattern="[0-9]{10}"
									maxlength="10"
									required>
							</div>

							<div class="col-md-4">
								<button
									type="submit"
									class="btn btn-warning"
									onclick="return confirm('Send test report?');">
									Send Test
								</button>
							</div>

						</form>

					<?php
					$send = 0;

					if ($send === 1) {
					?>
						<a
							href="?action=send_employees"
							class="btn btn-primary"
							onclick="return confirm('Send reports to all employees?');">
							Send Report to Employees
						</a>

						<a
							href="?action=send_dealers"
							class="btn btn-success">
							Send Report to Dealers
						</a>
					<?php
					}
					?>

					</div>






<?php

$action = $_GET['action'] ?? '';

/* -------------------------------------------------
   SEND TEST
------------------------------------------------- */

if ($action == 'send_test') {


    $name = trim($_POST['test_name'] ?? '');
    $mobile = trim($_POST['test_mobile'] ?? '');

    // Server-side validation
    if ($name == '') {
        die('Name is required.');
    }

    if (!preg_match('/^[0-9]{10}$/', $mobile)) {
        die('Please enter a valid 10-digit mobile number.');
    }
	
	$mobile = '91' . $mobile;

    $payload = [

        'to' => $mobile,

        'recipient_type' => 'individual',

        'type' => 'template',

        'template' => [

            'language' => [

                'policy' => 'deterministic',

                'code' => 'en'

            ],

            'name' => 'concord_gmp_account_statement',

            'components' => [

                [

                    'type' => 'body',

                    'parameters' => [

                        [

                            'type' => 'text',

                            'text' => $name

                        ],

                        [

                            'type' => 'text',

                            'text' => 'Google My Business (GMB) Report'

                        ]

                    ]

                ],

                [

                    'type' => 'button',

                    'sub_type' => 'url',

                    'index' => 0,

                    'parameters' => [

                        [

                            'type' => 'text',

                            'text' => 'https://rpt.kajariaceramics.com/dealer_dashboard.php?source2=OTcxNzc5NTA0OA%3D%3D'

                        ]

                    ]

                ]

            ]

        ]

    ];

    $curl = curl_init();

    curl_setopt_array($curl, [

        CURLOPT_URL =>
            'https://wa-crm.concordtechnosoft.com/api/meta/v19.0/282894604900917/messages',

        CURLOPT_RETURNTRANSFER => true,

        CURLOPT_TIMEOUT => 30,

        CURLOPT_POST => true,

        CURLOPT_POSTFIELDS => json_encode($payload),

        CURLOPT_HTTPHEADER => [

            'Content-Type: application/json',

            'Authorization: Bearer s513y3UNQnJVcXJvAZCCpfAuewkgQId3wJqH1d2uuNlRmqEHmICOHapxVU5ERVJTQ09SRQzdvKKm7ivfs2kMI5XiO6pD2JSCnKy0C6J015WGMgxiQfQqGSqv1REFTSAy7yoGq5qxNwvVUHLOTp1NVijNn2D9TBuVBoKsPxHmjE8No6yeTfHfWRqk2FpZNrq4KQbHw6jEFDX3p2pWZoxNfOR2ZnVU5ERVJTQ09SRQVU5ERVJTQ09SRQNu42Ax'

        ]

    ]);

    $response = curl_exec($curl);

    $error = curl_error($curl);

    curl_close($curl);

    echo '<div class="alert alert-info mt-3">';

    if ($error) {

        echo '<strong>Error:</strong><br>';
        echo htmlspecialchars($error);

    } else {

        echo '<strong>Response:</strong><br>';
        echo '<pre>';
        echo htmlspecialchars($response);
        echo '</pre>';

        echo '<hr>';

        echo '<a target="_blank" href="https://rpt.kajariaceramics.com/dealer_dashboard.php?source2=OTcxNzc5NTA0OA%3D%3D">';

        echo 'Open Report URL';

        echo '</a>';
    }

    echo '</div>';
}

/* -------------------------------------------------
   SEND TO EMPLOYEES
------------------------------------------------- */

if ($action == 'send_employees') {

    set_time_limit(0);

    $logDir = __DIR__ . '/sendlog';

    if (!is_dir($logDir)) {
        mkdir($logDir, 0777, true);
    }

    $timestamp = date('Ymd_His');

    $csvFilename =
        "employee_send_{$timestamp}.csv";

    $logFilename =
        "employee_send_{$timestamp}.log";

    $csvPath =
        $logDir . '/' . $csvFilename;

    $logPath =
        $logDir . '/' . $logFilename;

    $csv =
        fopen($csvPath, 'w');

    fputcsv($csv, [
        'Emp Code',
        'Name',
        'Mobile',
        'URL',
        'Status',
        'Response'
    ]);

    file_put_contents(
        $logPath,
        "Started : "
        . date('Y-m-d H:i:s')
        . PHP_EOL
    );

    $countSql = "
        SELECT COUNT(*) total
        FROM dealer_connected_employees
    ";

    $total =
        (int)$conn
            ->query($countSql)
            ->fetch_assoc()['total'];

    $sql = "
        SELECT
            emp_code,
            name,
            mobile1
        FROM dealer_connected_employees
        ORDER BY name 
    ";

    $res =
        $conn->query($sql);

    echo '<div class="alert alert-info">';
    echo '<strong>Processing...</strong><br>';
    echo 'Total Employees : '
         . $total;
    echo '</div>';

    flush();

    $processed = 0;

    while ($row = $res->fetch_assoc()) {

        $processed++;

        $empCode =
            trim($row['emp_code']);

        $name =
            trim($row['name']);

        $mobile =
            preg_replace(
                '/\D/',
                '',
                $row['mobile1']
            );

        $encodedEmpCode =
            enc($empCode);

        $reportUrl =
            'https://rpt.kajariaceramics.com/dealer_dashboard.php?source1='
            . $encodedEmpCode;

        $status =
            'Pending';

        $response =
            '';

        if (strlen($mobile) != 10) {

            $status =
                'Invalid Mobile';

        } else {

            $mobile = '91' . $mobile;
//            $mobile = '919582439353';			
			

            $payload = [

                'to' => $mobile,

                'recipient_type' =>
                    'individual',

                'type' =>
                    'template',

                'template' => [

                    'language' => [

                        'policy' =>
                            'deterministic',

                        'code' =>
                            'en'

                    ],

                    'name' =>
                        'concord_gmp_account_statement',

                    'components' => [

                        [
                            'type' => 'body',

                            'parameters' => [

                                [
                                    'type' => 'text',
                                    'text' => $name
                                ],

                                [
                                    'type' => 'text',
                                    'text' => 'Google My Business (GMB) Report'
                                ]

                            ]
                        ],

                        [
                            'type' => 'button',

                            'sub_type' => 'url',

                            'index' => 0,

                            'parameters' => [

                                [
                                    'type' => 'text',
                                    'text' =>  $reportUrl
                                ]

                            ]
                        ]

                    ]
                ]
            ];

            $curl =
                curl_init();

            curl_setopt_array(
                $curl,
                [

                    CURLOPT_URL =>
                        'https://wa-crm.concordtechnosoft.com/api/meta/v19.0/282894604900917/messages',

                    CURLOPT_RETURNTRANSFER =>
                        true,

                    CURLOPT_TIMEOUT =>
                        30,

                    CURLOPT_POST =>
                        true,

                    CURLOPT_POSTFIELDS =>
                        json_encode($payload),

                    CURLOPT_HTTPHEADER => [

                        'Content-Type: application/json',

                        'Authorization: Bearer s513y3UNQnJVcXJvAZCCpfAuewkgQId3wJqH1d2uuNlRmqEHmICOHapxVU5ERVJTQ09SRQzdvKKm7ivfs2kMI5XiO6pD2JSCnKy0C6J015WGMgxiQfQqGSqv1REFTSAy7yoGq5qxNwvVUHLOTp1NVijNn2D9TBuVBoKsPxHmjE8No6yeTfHfWRqk2FpZNrq4KQbHw6jEFDX3p2pWZoxNfOR2ZnVU5ERVJTQ09SRQVU5ERVJTQ09SRQNu42Ax'

                    ]

                ]
            );

            $response =
                curl_exec($curl);

            $error =
                curl_error($curl);

            curl_close($curl);

            if ($error) {

                $status =
                    'Failed';

                $response =
                    $error;

            } else {

                $status =
                    'Sent';
            }

            //sleep(1);
        }

        fputcsv($csv, [

            $empCode,
            $name,
            $mobile,
            $reportUrl,
            $status,
            $response

        ]);

        file_put_contents(

            $logPath,

            date('Y-m-d H:i:s')
            . " | "
            . $empCode
            . " | "
            . $name
            . " | "
            . $status
            . PHP_EOL,

            FILE_APPEND
        );

        if ($processed % 10 == 0) {

            $percent =
                round(
                    ($processed / $total)
                    * 100
                );

            echo "<div>";

            echo $processed
                 . " / "
                 . $total
                 . " processed ("
                 . $percent
                 . "%)";

            echo "</div>";

            flush();
        }
    }

    fclose($csv);

    file_put_contents(
        $logPath,
        PHP_EOL
        . "Completed : "
        . date('Y-m-d H:i:s'),
        FILE_APPEND
    );

    echo '<div class="alert alert-success mt-3">';

    echo '<h5>Completed</h5>';

    echo '<a download class="btn btn-primary me-2" target="_blank" href="sendlog/'
         . $csvFilename
         . '">Download CSV</a>';

    echo '<a download class="btn btn-secondary" target="_blank" href="sendlog/'
         . $logFilename
         . '">Download Log</a>';

    echo '</div>';
}

/* -------------------------------------------------
   SEND TO DEALERS
------------------------------------------------- */
if ($action == 'send_dealers') {

    echo '

    <div class="alert alert-warning">

        Dealer sending section
        will be added later.

    </div>

    ';
}
?>


<div class="container-fluid py-4">

    <div class="card shadow-sm border-0">

        <div class="card-body">

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

                <div>

                    <div class="page-title">
                        Employee Dealer Mapping
                    </div>

                    <div class="text-muted">
                        Employee hierarchy and connected dealer website IDs
                    </div>

                </div>

            </div>

            <div class="table-responsive">

								<a
									href="dealer_dashboard.php?source2=<?= enc('9717795048') ?>"
									class="text-decoration-none" target="_blank">

									All Records

								</a>



                <table
                    id="employeeTable"
                    class="table table-bordered table-hover align-middle">

                    <thead class="table-dark">

                        <tr>

                            <th>Emp Code</th>

                            <th>Name</th>

                            <th>Mobile</th>

                            <th>Level</th>

                            <th>Role</th>

                            <th>Reporting Code</th>

                            <th>Reporting Name</th>

                            <th>Reporting Mobile</th>

                            <th>Sales Office</th>

                            <th>Total Dealers</th>

                            <th>Connected Website IDs</th>

                        </tr>

                    </thead>

                    <tbody>

                    <?php
                    if ($res && $res->num_rows > 0) {

                        while ($row = $res->fetch_assoc()) {
                    ?>

                        <tr>

							<td>

								<a
									href="dealer_dashboard.php?source1=<?= enc($row['emp_code']) ?>"
									class="fw-bold text-decoration-none"  target="_blank">

									<?= htmlspecialchars($row['emp_code']) ?>

								</a>

							</td>
                            <td>
                                <?= htmlspecialchars($row['name']) ?>
                            </td>
							
							<td>

								<a
									href="dealer_dashboard.php?source2=<?= enc($row['mobile1']) ?>"
									class="text-decoration-none" target="_blank">

									<?= htmlspecialchars($row['mobile1']) ?>

								</a>

							</td>


                            <td>

                                <span class="badge bg-primary badge-level">

                                    <?= htmlspecialchars($row['level']) ?>

                                </span>

                            </td>

                            <td>
                                <?= htmlspecialchars($row['role_name']) ?>
                            </td>

                            <td>
                                <?= htmlspecialchars($row['reporting_to_emp_code']) ?>
                            </td>

                            <td>
                                <?= htmlspecialchars($row['reporting_to_name']) ?>
                            </td>

                            <td>
                                <?= htmlspecialchars($row['reporting_to_mobile1']) ?>
                            </td>

                            <td>
                                <?= htmlspecialchars($row['sales_off_desc']) ?>
                            </td>

                            <td>

                                <span class="badge bg-success">

                                    <?= (int)$row['total_dealers'] ?>

                                </span>

                            </td>

                            <td class="website-box">

                                <?php
											$websiteIds = explode(
												',',
												$row['connected_websites']
											);

											foreach ($websiteIds as $websiteId) {

												$websiteId = trim($websiteId);

												if (!$websiteId) {
													continue;
												}

												?>

												<a
													href="dealer_dashboard.php?source3=<?= enc($websiteId) ?>"
													target="_blank"
													class="text-decoration-none">

													<?= htmlspecialchars($websiteId) ?>

												</a>

												&nbsp;

												<?php
											}
											?>

                            </td>

                        </tr>

                    <?php
                        }
                    }
                    ?>

                    </tbody>

                </table>

            </div>

        </div>

    </div>

</div>

<!-- jQuery -->
<script
src="https://code.jquery.com/jquery-3.7.1.min.js">
</script>

<!-- Bootstrap -->
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js">
</script>

<!-- DataTables -->
<script
src="https://cdn.datatables.net/1.13.8/js/jquery.dataTables.min.js">
</script>

<script
src="https://cdn.datatables.net/1.13.8/js/dataTables.bootstrap5.min.js">
</script>

<script>

$(document).ready(function () {

    $('#employeeTable').DataTable({

        pageLength: 100,

        lengthMenu: [
            [50, 100, 250, 500, -1],
            [50, 100, 250, 500, "All"]
        ],

        ordering: true,

        searching: true,

        responsive: true

    });

});

</script>

</body>
</html>