<?php
session_start();
$activePage = 'User'; 
include("../elements/functions.php");

//-----------------DEFINE EXPECTED HEADERS ------------------------------------//

$expectedHeaders = ['PID', 'FIRSTNAME', 'LASTNAME', 'EMAIL', 'ROLE', 'PASSWORD'];

if (isset($_SESSION['token'])) {
    $token = $_SESSION['token'];
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_FILES['upload']) && $_FILES['upload']['error'] === UPLOAD_ERR_OK) {
            $fileTmpPath = $_FILES['upload']['tmp_name'];
            $fileName = $_FILES['upload']['name'];
            $fileSize = $_FILES['upload']['size'];
            $fileType = $_FILES['upload']['type'];
            $fileNameCmps = explode(".", $fileName);
            $fileExtension = strtolower(end($fileNameCmps));

            $allowedfileExtensions = array('csv');
            if (in_array($fileExtension, $allowedfileExtensions)) {
                $csvData = file_get_contents($fileTmpPath);
                $lines = explode("\n", $csvData);
                $headers = str_getcsv(array_shift($lines));

//---------------------------------------CHECK IF THE HEADERS MATCH ----------------------//

                $headerMismatch = array_diff($expectedHeaders, $headers);
                if (!empty($headerMismatch) || count($headers) != count($expectedHeaders)) {
                    $_SESSION['error'] = "Unsupported CSV structure. Required headers: " . implode(", ", $expectedHeaders);
                    header("Location: ../user/upload_summary.php");
                    exit();
                }

                

                $users = [];
                foreach ($lines as $line) {
                    $row = str_getcsv($line);
                    if (count($row) == count($headers)) {
                        $user = array_combine($headers, $row);
                        $users[] = $user;
                    }
                }

                $successCount = 0;
                $errorCount = 0;
                $existingCount = 0;
                $deleteCount = 0;
                $passwordCount =0;
                $existingUsers =[];
                $deletedUsers =[];
                $passwordMissing =[];

                foreach ($users as $user) {
                    $pid = $user['PID'];
                    $firstname = $user['FIRSTNAME'];
                    $lastname = $user['LASTNAME'];
                    $email = $user['EMAIL'];
                    $role = $user['ROLE'];
                    $password = $user['PASSWORD'];


                if(!empty($password)){
                    
//---------------------------API CALL FOR USER CREATION-----------------------//
                    $jsonFilePath = __DIR__ . '/../urls/api_endpoints.json';
                    $jsonData = file_get_contents($jsonFilePath);
                    $endpoints = json_decode($jsonData, true);
                    $url = $endpoints['user'];
//--------------------------------------API CALL ENDS--------------------------//

                    $data = [
                        "pid" =>  $pid,
                        "firstname" => $firstname,
                        "lastname" => $lastname,
                        "email" => $email
                    ];

                    $response = make_post_request($url, $data);

                    if ($response === FALSE) {
                        $errorCount++;
                        continue;
                    }

                    $response_data = json_decode($response, true);

                   
                    if ($response_data['status'] === 201) {
                        $successCount++;

 //-------------------------- CONVERTION OF ROLE--------------------------------------------//

                     $roleConverted = strtolower($role);
                     if ($roleConverted === 'guest') {
                         $role = 'guest';

//------------------------CONVERTION ENDS HERE--------------------------------------------//

//--------------------------------------API CALL FOR PASSWORD CREATION-----------------------//
                        $jsonFilePath = __DIR__ . '/../urls/api_endpoints.json';
                        $jsonData = file_get_contents($jsonFilePath);
                        $endpoints = json_decode($jsonData, true);
                        $url = $endpoints['password_function'] . $pid . "/password?";
//--------------------------------------------API CALL ENDS-------------------------------//

                         $data = [
                             "access_level" =>  "NONE",
                             "password" => $password,
                             "pid" => $pid,
                             "expiration" => '',
                             "valid_from" => date('Y-m-d'),      
                             "category" => "1",
                             "access_duration" => "1D" 
                             ];
                         $response =  make_post_request($url, $data);
                         continue;         
//---------------------------------------ROLE GUEST ENDS ----------------------------------------//

//--------------------------------------ROLE USER STARTS--------------------------------------------//
                     } else {
                         $role = 'User';    
//------------------------------------API CALL FOR PASSWORD CREATION----------------------------------//

                                 $jsonFilePath = __DIR__ . '/../urls/api_endpoints.json';
                                 $jsonData = file_get_contents($jsonFilePath);
                                 $endpoints = json_decode($jsonData, true);
                                 $url = $endpoints['password_function'] . $pid . "/password?";

//------------------------------------------API CALL FOR PASSWORD ENDS HERE----------------------------//

                                  $data = [
                                      "access_level" =>  "NONE",
                                      "password" => $password,
                                      "pid" => $pid,
                                      "expiration" => date('Y-m-d', strtotime('+3 years')),
                                      "valid_from" => date('Y-m-d'),      
                                      "category" => "6",
                                      "access_duration" => "" 
                                  ];
                                $response =  make_post_request($url, $data);
                                if ($response === FALSE) {
                                  $errorCount++;
                                  continue;
                                                }               
                          
                     }
                    } elseif ($response_data['status'] === 409) {
                        $existingCount++;
                        $existingUsers[] = $pid;
                    } else {
                        $errorCount++;
                    }

                }

                if(empty($password)){
                    $passwordCount++;
                    $passwordMissing[] =$pid;
                    continue;
                }

                }

                if (!empty($existingUsers)) {
                    if (!is_dir(__DIR__ . '/../downloads')) {
                        mkdir(__DIR__ . '/../downloads', 0777, true);
                    }
                    $csvFile = __DIR__ . '/../downloads/existing_users.csv';
                    $fileHandle = fopen($csvFile, 'w');
                    if ($fileHandle === FALSE) {
                        die('Failed to create CSV file.');
                    }
                    fputcsv($fileHandle, ['PID']);
                    foreach ($existingUsers as $pid) {
                        fputcsv($fileHandle, [$pid]);
                    }
                    fclose($fileHandle);
                }

                
                if (!empty($passwordMissing)) {
                    if (!is_dir(__DIR__ . '/../downloads')) {
                        mkdir(__DIR__ . '/../downloads', 0777, true);
                    }
                    $csvFile = __DIR__ . '/../downloads/deleted_users.csv';
                    $fileHandle = fopen($csvFile, 'w');
                    if ($fileHandle === FALSE) {
                        die('Failed to create CSV file.');
                    }
                    fputcsv($fileHandle, ['PID']);
                    foreach ($passwordMissing as $pid) {
                        fputcsv($fileHandle, [$pid]);
                    }
                    fclose($fileHandle);
                }


                $_SESSION['successCount'] = $successCount;
                $_SESSION['passwordCount'] = $passwordCount;
                $_SESSION['csvFile'] = !empty($existingUsers) ? 'existing_users.csv' : '';
                $_SESSION['passwordFile'] =!empty($passwordMissing) ? 'password_miss.csv' : '';

                header("Location: ../user/upload_summary.php");
                exit();
            }
        }
    }
}
?>
