<?php

//upload.php

set_time_limit(0);
ini_set('display_errors', 1);

include 'pagename.php';

include $session;

Session::checkSession_app();

include '../config.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$error = '';
$html = '';
$check_mailbox = '';
$csv_new_name = '';

$log->system_debug("Starting upload process...");

if (isset($_FILES['file']['name'])) {
    $file_name = $_FILES['file']['name'];
    $file_size = $_FILES['file']['size'] / (1024 * 1024); // Convert file size to MB
    $file_type = $_FILES['file']['type'];
    $file_tmp = $_FILES['file']['tmp_name'];
    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
    $allowed_extensions = array("csv");

    $log->system_debug("File details - Name: $file_name, Size: $file_size MB, Type: $file_type, Extension: $file_ext");

    if (!in_array($file_ext, $allowed_extensions)) {
        $error = "Extension not allowed, please choose a CSV file.";
        $log->system_debug("Error: $error");
    } else {
        $tmploc = realpath(dirname(dirname(__FILE__))) . '/tmp/csv/';
        $file_path = $tmploc . $file_name;

        if (move_uploaded_file($file_tmp, $file_path)) {
            $log->system_debug("File moved to: $file_path");

            if (($file_data = fopen($file_path, 'r')) !== false) {
                $file_header = fgetcsv($file_data, 0, ",", "\"", "\\");
                $log->system_debug("File header: " . implode(',', $file_header));

                $cc_data = unserialize($_POST['cc_data']);
                $log->system_debug("cc_data: " . json_encode($cc_data)); // Debug log for cc_data

                $data = '';
                if (!empty($cc_data)) {
                    foreach ($cc_data as $val) {
                        $Uval = ucwords(str_replace('_', ' ', $val));
                        $data .= "<option value='$val'>$Uval</option>";
                    }
                }
                $html .= '<div class="form-group">
                <label for="csv_new_name">CSV File Custom Name (optional):</label>
                <input type="text" name="csv_new_name" id="csv_new_name" class="form-control" placeholder="Enter custom name for the CSV file">
              </div>';

                $html .= '<table class="table table-bordered"><tr>';
                foreach ($file_header as $count => $header) {
                    $html .= '
                    <th>
                        <select name="set_column_data" class="form-control set_column_data" data-column_number="' . $count . '">
                        <option value="">Set Data</option>'
                        . $data .
                        '<option value="email_name">Email</option>
                        </select>
                    </th>';
                }
                $html .= '</tr>';

                $limit = 0;
                $temp_data = [];
                while (($row = fgetcsv($file_data, 0, ",", "\"", "\\")) !== false) {
                    $limit++;
                    if ($limit < 2) {
                        $html .= '<tr>';
                        foreach ($row as $cell) {
                            $html .= '<td>' . $cell . '</td>';
                        }
                        $html .= '</tr>';
                    }
                    $temp_data[] = $row;
                }

                $_SESSION['file_data'] = $temp_data;
                $_SESSION['file_name'] = $file_name;
                $_SESSION['file_size'] = $file_size;

                if ($_POST['inbox_checker'] == 'true') {
                    $check_mailbox = '<div align="left">
                                        <div class="form-group row">
                                        <label class="col-sm-4 col-form-label">Confirm Mailbox <i class="icon-copy dw dw-question-1" data-container="addList" data-toggle="tooltip" data-placement="top" data-original-title="Send actual dummy emails to this list for second level validation. Make sure your dummy imap & smtp email account already configured!"></i><p style="font-size: 14px;line-height: 1em;width: 80%;"><small>
                                                Fully validate mailbox by sending actual dummy emails to this list. Make sure your dummy imap &amp; smtp email account already configured!
                                            </small></p></label>
                                        <div class="col-sm-8">
                                            <label class="btn_switch">
                                            	<input type="checkbox" name="check_mailbox" id="check_mailbox" value="false">
								                <span class="btn_slider round"></span>
                                            </label>
                                        </div>
                                      </div>
                                    </div>';
                }
                $html .= '</table><br />';
                $html .= $check_mailbox . '<div align="right">
                            <button type="button" name="import" id="import" class="btn btn-success" disabled>Import</button>
                          </div><br />';
                $log->system_debug("HTML generated successfully");
            } else {
                $error = 'Failed to open the uploaded file.';
                $log->system_debug("Error: $error");
            }
        } else {
            $error = 'Failed to move uploaded file';
            $log->system_debug("Error: $error");
        }
    }
} else {
    $error = 'No file uploaded';
    $log->system_debug("Error: $error");
}

$output = array(
    'error' => $error,
    'output' => $html,
    'csv_file' => isset($file_name) ? $file_name : ''
);

echo json_encode($output);
// $log->system_debug("Output: " . json_encode($output));

?>