<?php
ini_set('display_errors', 1);
ini_set('memory_limit', '1024M');
ini_set('max_execution_time', 600);

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
use PhpOffice\PhpSpreadsheet\IOFactory;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    require_once '../../../../../resources/base_path_include.php';
    require_once $base_path_to_learning_resources . "includes/connect.php";
    require_once $base_path_to_learning_resources . 'lib/function.php';
    require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';
    require_once $base_path_to_learning_resources . 'lib/validate_function.php';
    require_once $base_path_to_learning . '/user_management/check_username_availability.php';
    require_once $base_path_to_learning . 'user_management/authenticate.php';
    require_once $base_path_to_learning . 'admin_api/modules/students/student_functions.php';
    require_once $base_path_to_learning . 'user_management/faculty/functions.php';
    require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
    require_once $base_path_to_learning . 'admin_api/modules/student_registration/functions/functions.php';
    require_once $base_path_to_learning . "vendor/autoload.php";
    require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
    require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
    require_once $base_path_to_learning . 'functions/common_functions.php';
    require_once $base_path_to_learning . 'functions/cache_student_academic_function.php';
    require_once $base_path_to_learning_resources . 'external_requests/finware_curl/groups_ledgers/curl_add_alter_student_ledgers_finware.php';
    require_once $base_path_to_learning_resources . 'external_requests/finware_curl/groups_ledgers/curl_function_branch_students.php';
    require_once $base_path_to_learning_resources . 'lib/common_modules/import/student_data/function.php';

    // Helper function for error logging using file_put_contents (append)
    function logError($message, $file = 'import_errors.log') {
        $date = date("Y-m-d H:i:s");
        $formattedMessage = "[$date] $message\n";
        file_put_contents($file, $formattedMessage, FILE_APPEND);
    }

    $user_id = $_POST['user_id'] ?? '';
    $workspace_id = $_POST['workspace_id'] ?? '';
    $username = $_POST['username'] ?? '';
    $role = $_POST['role'] ?? '';
    $institution_id = $_POST['institution_id'] ?? '';

    $errorLogPath = 'import_errors.log';

    try {
        validateApiSignature($_POST['api_signature'] ?? '');

        $specific_db_name = validateUserAccess($conn_rjllearning, $user_id, $role, $workspace_id, ['superadmin', 'admin'], null);
        if (!$specific_db_name) {
            echo json_encode(["status" => 0, "response" => "Access Denied."]);
            exit;
        }

        $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);

        $academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
        if ($academic_id == false) {
            echo json_encode(["status" => 0, "response" => "Access denied. Academic session not active."]);
            exit;
        }

        if (!isset($_FILES['excel_file']) || $_FILES['excel_file']['error'] !== 0) {
            echo json_encode(["status" => 0, "response" => "File upload failed."]);
            exit;
        }

        $excelFilePath = $_FILES['excel_file']['tmp_name'];

        $spreadsheet = IOFactory::load($excelFilePath);
        $sheet = $spreadsheet->getActiveSheet();
        $rows = $sheet->toArray();

        $header = array_map('strtolower', $rows[0]);
        unset($rows[0]);

        $stmtStudent = $conn_rjllearning_specific->prepare(
            "SELECT id FROM students WHERE admission_number = ? AND institution_id = ? AND branch_id = ?"
        );

        $conn_rjllearning_specific->beginTransaction();
        logError("---- Import started ----", $errorLogPath);

        foreach ($rows as $index => $row) {
            try {
                $data = array_combine($header, $row);
              
                $branch_id = getBranchId($conn_rjllearning_specific, $institution_id, trim($data['branch_name'] ?? ''));
                $admission_no = trim($data['admission_no'] ?? '');
                $profile_photo = trim($data['profile_photo'] ?? '');
                $debugInfo = "branch_id: $branch_id\nadmission_no: $admission_no\nprofile_photo: $profile_photo\n";
file_put_contents('debug_log.txt', $debugInfo, FILE_APPEND);

// Skip row if profile_photo is empty
if (empty($profile_photo)) {
    file_put_contents('debug_log.txt', "Row skipped due to empty profile_photo\n", FILE_APPEND);
    continue;  // Skip this row, go to next
}

                if (!$institution_id || !$branch_id || !$admission_no || !$profile_photo) {
                    logError("Row " . ($index + 2) . ": Missing required data", $errorLogPath);
                    continue; // skip this row but continue import
                }

                $stmtStudent->execute([$admission_no, $institution_id, $branch_id]);
                $student = $stmtStudent->fetch();

                if (!$student) {
                    logError("Row " . ($index + 2) . ": Student not found", $errorLogPath);
                    continue;
                }

                $student_id = $student['id'];

                // if (!empty($profile_photo)) {
                //     copyImageFromAnotherBucketAndUpdate(
                //         $conn_rjllearning_specific,
                //         $s3_learning_bucket,
                //         $learning_bucketName,
                //         $profile_photo,
                //         $workspace_id,
                //         $institution_id,
                //         $student_id,
                //         '' // sourceBucket blank if undefined
                //     );
                // }
            } catch (Exception $e) {
                logError("Row " . ($index + 2) . ": Exception - " . $e->getMessage(), $errorLogPath);
            }
        }

        $conn_rjllearning_specific->commit();
        logError("---- Import ended ----\n", $errorLogPath);

        echo json_encode(["status" => 1, "response" => "✅ Import completed successfully."]);
    } catch (Exception $e) {
        if (isset($conn_rjllearning_specific) && $conn_rjllearning_specific->inTransaction()) {
            $conn_rjllearning_specific->rollBack();
        }
        logError("Fatal Exception: " . $e->getMessage(), $errorLogPath);
        echo json_encode(["status" => 0, "response" => "❌ Import failed: " . $e->getMessage()]);
    }
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
  <title>Import Profile Photos</title>
  <style>
    #progressContainer {
      width: 100%;
      background: #ddd;
      border-radius: 5px;
      margin: 20px 0;
    }
    #progressBar {
      width: 0%;
      height: 20px;
      background: green;
      border-radius: 5px;
      color: white;
      text-align: center;
    }
  </style>
</head>
<body>
  <h2>Import Excel for Profile Photos</h2>
  <form id="uploadForm">
    <label>Workspace ID:</label><br>
    <input type="text" name="workspace_id" required><br><br>

    <label>Institution ID:</label><br>
    <input type="text" name="institution_id" required><br><br>

    <label>Username:</label><br>
    <input type="text" name="username" required><br><br>

    <label>User ID:</label><br>
    <input type="text" name="user_id" required><br><br>

    <label>API Signature:</label><br>
    <input type="text" name="api_signature" required><br><br>

    <label>Role:</label><br>
    <select name="role" required>
      <option value="superadmin">Superadmin</option>
      <option value="admin">Admin</option>
      <option value="staff">Staff</option>
    </select><br><br>

    <label>Select Excel File:</label><br>
    <input type="file" name="excel_file" accept=".xlsx,.xls" required><br><br>

    <input type="submit" value="Upload and Import">
  </form>

  <div id="progressContainer">
    <div id="progressBar">0%</div>
  </div>

  <div id="status"></div>

  <script>
    const form = document.getElementById('uploadForm');
    const progressBar = document.getElementById('progressBar');
    const statusDiv = document.getElementById('status');

    form.addEventListener('submit', function (e) {
      e.preventDefault();

      const formData = new FormData(form);
      const xhr = new XMLHttpRequest();

      xhr.open('POST', '', true);

      xhr.upload.onprogress = function (e) {
        if (e.lengthComputable) {
          const percentComplete = Math.round((e.loaded / e.total) * 100);
          progressBar.style.width = percentComplete + '%';
          progressBar.textContent = percentComplete + '%';
        }
      };

      xhr.onload = function () {
        if (xhr.status === 200) {
          try {
            const response = JSON.parse(xhr.responseText);
            progressBar.style.width = '100%';
            progressBar.textContent = '100%';
            statusDiv.innerHTML = `<p><strong>${response.response}</strong></p>`;
          } catch {
            statusDiv.innerHTML = `<p><strong>❌ Invalid server response.</strong></p>`;
          }
        } else {
          statusDiv.innerHTML = `<p><strong>❌ Error during import.</strong></p>`;
        }
      };

      xhr.onerror = function () {
        statusDiv.innerHTML = `<p><strong>❌ Upload failed. Check connection.</strong></p>`;
      };

      xhr.send(formData);
    });
  </script>
</body>
</html>
