<?php
require_once '../config.php';
session_start();


// Check if the user is logged in as a system admin
$connection = mysqli_connect($db_host, $db_user, $db_password, $db_name);

// Set the character set to UTF-8 to avoid collation conflicts
mysqli_set_charset($connection, "utf8mb4");

// Check if user is logged in as a member
if (!isset($_SESSION['userType']) || $_SESSION['userType'] !== 'member') {
    header('Location: ../indexX.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!empty($_FILES['csv_file']['tmp_name'])) {
		//retrieve induction date 
		$inductionDate = $_POST["induction_date"];
        // Retrieve the uploaded CSV file
        $csvFile = $_FILES['csv_file']['tmp_name'];

        // Process the CSV file and store the data for preview
        $previewData = processCSVFile($csvFile, $connection);
        $nomineeCount = count($previewData);
      //  echo 'nomineeCount '.$nomineeCount;

        // Retrieve the user ID
        $userId = $_SESSION['id'];

        // Retrieve user information and credits
        $query = "SELECT zone, credits FROM users WHERE id = ?";
        $stmt = mysqli_prepare($connection, $query);
        mysqli_stmt_bind_param($stmt, "i", $userId);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);

        $zoneMinistryCentre = "";
        $credit = 0;

        if ($result) {
            $row = mysqli_fetch_assoc($result);
            $zoneMinistryCentre = $row['zone'];
            $credit = $row['credits'];
        }

      //  echo 'my credit '.$credit;

        // Store the preview data in session for later use
        $_SESSION['previewData'] = $previewData;

        if ($nomineeCount < $credit)

        {// Redirect to the preview page
            header('Location: bulk_upload_preview.php?induct_date='.$inductionDate);
            exit;
          }

        elseif ($nomineeCount > $credit)

          {// Redirect to the preview page
              $message =  'Insufficient credits! <p>Your credit count is '.$credit;
            }

    } else {
        echo "Please select a CSV file.";
    }
}


// Function to process the uploaded CSV file and return the data for preview
function processCSVFile($csvFile, $connection) {
    $previewData = array();

    // Open the CSV file for reading
    if (($handle = fopen($csvFile, 'r')) !== false) {
        // Read the CSV file line by line
        while (($data = fgetcsv($handle, 0, ',', '"', '\\')) !== false) {
            // Sanitize and store the row data
            $row = array();
            foreach ($data as $value) {
                // Convert UTF-8 to Latin1 to match database collation
                $convertedValue = mb_convert_encoding($value, 'ISO-8859-1', 'UTF-8');
                $row[] = sanitizeInput($connection, $convertedValue); // Pass the $connection parameter
            }
            $previewData[] = $row;
        }

        fclose($handle);
    }

    return $previewData;
}

// Helper function to sanitize input
function sanitizeInput($connection, $input) {

    // Check if the input is an array
    if (is_array($input)) {
        // Sanitize each element of the array
        foreach ($input as &$value) {
            $value = sanitizeInput($connection, $value); // Pass the $connection parameter
        }
        unset($value); // unset the reference to the last element
    } else {
        // Escape special characters in the input string
        $input = mysqli_real_escape_string($connection, $input);

        // You can apply additional sanitization or validation logic here if needed
        // For example, you can use regular expressions or specific filters

        // Return the sanitized input
        return $input;
    }
}

include('../headerspecial.php');

?>

<!DOCTYPE html>
<html>
<head>
    <title>File Upload</title>
</head>
<body>
  <?php
  if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($nomineeCount > $credit) {echo '<div style="background-color: red;text-align:center;"><p>&nbsp;<p>'.$message.'<p>&nbsp;<p></div>';}
  }

    ?>

<h2>Nominees Data Upload</h2><p>
  Please upload the nominees data using the form below.<p>
  The template (CSV) is accessible via this <a href ="cell_nominee_template.csv">link.</a>
    <form method="post" enctype="multipart/form-data">
        Induction Date:<br><input type="date" name="induction_date"><p>
		Nominees Data (CSV only):<br><input type="file" name="csv_file">
        <input type="submit" value="Upload">
    </form>
</body>
</html>
