<?php
session_start(); 
include("../include/config.php");
include("../include/functions.php");
validate_admin();

if($_SESSION['sess_admin_id']){
    $sql = $obj->query("select * from $tbl_admin where id=".$_SESSION['sess_admin_id']);
    $result = $obj->fetchNextObject($sql);
}
?>
<?php
if (isset($_POST['upload_csv'])) {

    set_time_limit(0);

    if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] != 0) {
        echo "❌ File upload error!";
        exit;
    }

    $fileTmpPath = $_FILES['csv_file']['tmp_name'];

    $apiUrl = "https://api-03.moengage.com/v1/customer/delete?app_id=NZSDWSXRSQMTPAXO4V5K0ONO_DEBUG";
    $authKey = "fYmD9XH9rxkTObgNCzt5bOxF";

    if (($handle = fopen($fileTmpPath, "r")) !== false) {

        fgetcsv($handle); // skip header
        $count = 0;

        while (($row = fgetcsv($handle, 1000, ",")) !== false) {

            echo $customer_id = trim($row[0]);

            if (empty($customer_id)) continue;

            $data = [
                "identity_type" => "customer_id",
                "identity_value" => $customer_id
            ];

            $ch = curl_init($apiUrl);

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);

            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                "Authorization: $authKey",
                "Content-Type: application/json"
            ]);

            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

            $response = curl_exec($ch);

            if (curl_errno($ch)) {
                echo "❌ Error for $customer_id : " . curl_error($ch) . "<br>";
            } else {
                echo "✅ Deleted: $customer_id | Response: $response <br>";
            }

            curl_close($ch);

            $count++;

            usleep(200000); // delay
        }

        fclose($handle);

        echo "<h3>🎯 Total Processed: $count</h3>";

    } else {
        echo "❌ CSV file open nahi hui!";
    }
}
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo SITE_TITLE; ?></title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<link href="css/admin.css" rel="stylesheet" type="text/css" />

<style>
.error { color: red; font-size: 13px; }
.success { color: green; font-size: 13px; }

.submit {
    background-color: #0971a2;
    color: #fff;
    font-size: 12px;
    font-weight: bold;
    height: 30px;
    border-radius: 5px;
    cursor: pointer;
    border: none;
}
</style>

</head>

<body>

<table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">

<?php include("header.php") ?>

<tr>
<td align="right" valign="top" class="paddRtLt70">

<table width="99%" border="0" cellpadding="0" cellspacing="0">

<tr>
<td class="headingbg bodr text14">
    <img src="images/arrow2.gif" width="21" height="21" align="absmiddle" />
    Admin: Upload CSV file
</td>
</tr>

<tr>
<td bgcolor="#f3f4f6" class="bodr" valign="top">

<table width="100%" cellpadding="0" cellspacing="0">

<tr>
<td colspan="2" align="center">
    <font color="red"><strong><?php echo $_SESSION['sess_msg']; $_SESSION['sess_msg']='';?></strong></font>
</td>
</tr>

<tr>
<td width="18%" align="right"><strong>Username:</strong></td>
<td><?php echo $result->username;?></td>
</tr>

<tr>
<td></td>
<td>

<form id="" method="POST" enctype="multipart/form-data">

    <input type="hidden" name="submitForm" value="yes">

    <input type="file" id="csvFile" name="csv_file" required accept=".csv">

    <div id="errorMsg" class="error"></div>
    <div id="successMsg" class="success"></div>

    <br>

    <input type="submit" value="Submit" name="upload_csv" class="submit">
    <input type="reset" value="Reset" class="submit">

</form>

</td>
</tr>

</table>

</td>
</tr>

</table>

</td>
</tr>

<?php include('footer.php'); ?>

</table>

<script>
const form = document.getElementById("uploadForm");
const fileInput = document.getElementById("csvFile");
const errorMsg = document.getElementById("errorMsg");
const successMsg = document.getElementById("successMsg");

form.addEventListener("submit", function(e) {
    e.preventDefault();

    errorMsg.textContent = "";
    successMsg.textContent = "";

    const file = fileInput.files[0];

    if (!file) {
        errorMsg.textContent = "Please select a CSV file.";
        return;
    }

    if (!file.name.toLowerCase().endsWith(".csv")) {
        errorMsg.textContent = "Only CSV files are allowed.";
        return;
    }

    if (file.size > 2 * 1024 * 1024) {
        errorMsg.textContent = "File must be less than 2MB.";
        return;
    }

    const reader = new FileReader();

    reader.onload = function(e) {
        const content = e.target.result;

        if (!content.includes(",")) {
            errorMsg.textContent = "Invalid CSV format.";
            return;
        }

        successMsg.textContent = "File uploaded successfully";
    };

    reader.readAsText(file);
});


form.addEventListener("reset", function() {
    errorMsg.textContent = "";
    successMsg.textContent = "";

    fileInput.value = "";
});
</script>

</body>
</html>