<?php
require '../vendor/autoload.php';
include "../config/connect.php";

$id = isset($_GET['id']) ? intval($_GET['id']) : 0; // Validasi dan sanitasi input

// Cek apakah ID valid
if ($id <= 0) {
    http_response_code(400); // Bad Request
    echo json_encode(['status' => 'error', 'message' => 'ID tidak valid.']);
    exit;
}

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date;

$response = ['status' => 'success', 'dataValid' => [], 'dataError' => []];

// Batasi ukuran file upload
if (isset($_FILES['file']) && $_FILES['file']['size'] <= 2 * 1024 * 1024) { // Maksimal 2MB
    $file = $_FILES['file']['tmp_name'];

    // Validasi jenis file
    $fileType = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
    if (!in_array($fileType, ['xls', 'xlsx'])) {
        http_response_code(400); // Bad Request
        echo json_encode(['status' => 'error', 'message' => 'Jenis file tidak valid.']);
        exit;
    }

    // Membaca file Excel
    $spreadsheet = IOFactory::load($file);
    $sheet = $spreadsheet->getActiveSheet();

    // Ambil data mikrotik dari database
    $mikrotik = [];
    $stmt = $pdo->prepare("SELECT id, nama FROM setting_mikrotik WHERE id_data_server = :id");
    $stmt->execute([':id' => $id]);
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $mikrotik[$row['nama']] = $row['id'];
    }

    // Ambil data paket dari database
    $paket = [];
    $stmt = $pdo->prepare("SELECT id, nama FROM profile_paket WHERE id_data_server = :id");
    $stmt->execute([':id' => $id]);
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $paket[$row['nama']] = $row['id'];
    }

    // Ambil data user dari database
    $marketing = [];
    $stmt = $pdo->prepare("SELECT id, nama FROM user_akses WHERE id_data_server = :id");
    $stmt->execute([':id' => $id]);
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $marketing[$row['nama']] = $row['id'];
    }

    // Ambil data tagihan dari database
    $tagihan = [];
    $stmt = $pdo->prepare("SELECT id, nama FROM profile_tagihan WHERE id_data_server = :id");
    $stmt->execute([':id' => $id]);
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $tagihan[$row['nama']] = $row['id'];
    }

    // Ambil data pelanggan dari database
    $pelanggan = [];
    $niks = [];
    $stmt = $pdo->prepare("SELECT email, nik FROM pelanggan WHERE id_data_server = :id");
    $stmt->execute([':id' => $id]);
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $pelanggan[] = $row['email'];
        $niks[] = $row['nik'];
    }

    // Inisialisasi array untuk menyimpan data yang akan diinsert
    $insertData = [];
    
    // Loop melalui setiap baris di sheet, mulai dari baris kedua
    $rowIndex = 0;
    foreach ($sheet->getRowIterator() as $row) {
        if ($rowIndex == 0) {
            $rowIndex++;
            continue;
        }

        $cellIterator = $row->getCellIterator();
        $cellIterator->setIterateOnlyExistingCells(false);
        $data = [];

        foreach ($cellIterator as $cell) {
            if (Date::isDateTime($cell)) {
                $value = Date::excelToDateTimeObject($cell->getValue());
                $data[] = $value->format('Y-m-d');
            } else {
                $data[] = htmlspecialchars($cell->getValue(), ENT_QUOTES, 'UTF-8'); // Sanitasi output
            }
        }

        // Cek validitas data dan ambil ID yang sesuai
        $id_mikrotik = $mikrotik[$data[0]] ?? false;
        $id_paket = $paket[$data[1]] ?? false;
        $id_marketing = $marketing[$data[2]] ?? false;
        $id_tagihan = $tagihan[$data[3]] ?? false;
        $email_pelanggan = $data[11] ?? false; // Mengambil email dari data
        $nik_pelanggan = $data[6] ?? false; // Mengambil NIK dari data

        // Cek apakah email dan NIK pelanggan ada dalam array
        $is_email_valid = !in_array($email_pelanggan, $pelanggan);
        $is_nik_valid = !in_array($nik_pelanggan, $niks);

        // Cek apakah ada elemen kosong dalam data
        $hasEmptyValue = false;
        foreach ($data as $index => $value) {
            if (empty($value) && $value !== '0') {
                $hasEmptyValue = true;
                $elementNum = $index + 1;
                $response['dataError'][] = [
                    'name' => htmlspecialchars($data[5] ?? 'Tidak ada nama', ENT_QUOTES, 'UTF-8'), // Sanitasi output
                    'errorType' => "Kolom ke $elementNum Kosong"
                ];
                break;
            }
        }

        if ($id_mikrotik && $id_paket && $id_marketing && $id_tagihan && $is_email_valid && $is_nik_valid && !$hasEmptyValue) {
            $dataArray = array_merge([$id_mikrotik, $id_paket, $id_marketing, $id_tagihan], array_slice($data, 4));
            // Menyimpan data untuk batch insert
            $insertData[] = $dataArray;
        } else {
            // Inisialisasi array untuk menyimpan error berdasarkan nama
            $errorTypes = [];

            // Cek validitas masing-masing data
            if (!$id_mikrotik) {
                $errorTypes[] = 'Nama Mikrotik tidak valid';
            }
            if (!$id_paket) {
                $errorTypes[] = 'Nama Paket tidak valid';
            }
            if (!$id_marketing) {
                $errorTypes[] = 'Nama Marketing tidak valid';
            }
            if (!$id_tagihan) {
                $errorTypes[] = 'Nama Tagihan tidak valid';
            }
            if (!$is_email_valid || !$is_nik_valid) {
                $errorTypes[] = 'Pelanggan sudah terdaftar';
            }

            // Jika ada error, masukkan ke response
            if (!empty($errorTypes)) {
                $response['dataError'][] = [
                    'name' => htmlspecialchars($data[5] ?? 'Tidak ada nama', ENT_QUOTES, 'UTF-8'), // Sanitasi output
                    'errorType' => implode(', ', $errorTypes) // Gabungkan error dengan koma
                ];
            }
        }

        $rowIndex++;
    }

    // Jika ada data yang valid, lakukan batch insert
    if (!empty($insertData)) {
        // Persiapkan query SQL untuk batch insert
        $sql = "INSERT INTO pelanggan (
                    id_data_server,
                    id_setting_mikrotik,
                    id_profile_paket,
                    id_marketing,
                    id_profile_tagihan,
                    jenis_layanan,
                    nama,
                    nik,
                    alamat,
                    latitude,
                    longitude,
                    nomor_whatsapp,
                    email,
                    status,
                    time_start,
                    akun,
                    user_hotspot
                ) VALUES ";

        // Buat placeholder untuk setiap set data
        $valueSets = [];
        $params = [];
        foreach ($insertData as $index => $dataArray) {
            $placeholders = "(:id_data_server_$index, :id_setting_mikrotik_$index, :id_profile_paket_$index, :id_marketing_$index, :id_profile_tagihan_$index, :jenis_layanan_$index, :nama_$index, :nik_$index, :alamat_$index, :latitude_$index, :longitude_$index, :nomor_whatsapp_$index, :email_$index, :status_$index, :time_start_$index, :akun_$index, :user_hotspot_$index)";
            $valueSets[] = $placeholders;

            $hotspot = ($dataArray[15] === 'null' || $dataArray[15] === null) ? NULL : $dataArray[14];

            // Mengumpulkan parameter untuk binding
            $params = array_merge($params, [
                ":id_data_server_$index" => $id,
                ":id_setting_mikrotik_$index" => $dataArray[0],
                ":id_profile_paket_$index" => $dataArray[1],
                ":id_marketing_$index" => $dataArray[2],
                ":id_profile_tagihan_$index" => $dataArray[3],
                ":jenis_layanan_$index" => $dataArray[4],
                ":nama_$index" => $dataArray[5],
                ":nik_$index" => $dataArray[6],
                ":alamat_$index" => $dataArray[7],
                ":latitude_$index" => $dataArray[8],
                ":longitude_$index" => $dataArray[9],
                ":nomor_whatsapp_$index" => $dataArray[10],
                ":email_$index" => $dataArray[11],
                ":status_$index" => $dataArray[12],
                ":time_start_$index" => $dataArray[13],
                ":akun_$index" => $dataArray[14],
                ":user_hotspot_$index" => $hotspot
            ]);
        }

        // Gabungkan ke dalam query
        $sql .= implode(', ', $valueSets);

        // Persiapkan statement
        $stmt = $pdo->prepare($sql);
        
        // Eksekusi batch insert
        $stmt->execute($params);

        // Tambahkan data yang valid ke response
        $response['dataValid'] = $insertData; // Menyimpan semua data yang valid
    }

    // Kirim response sebagai JSON
    header('Content-Type: application/json');
    echo json_encode($response);
} else {
    http_response_code(400); // Bad Request
    $response['status'] = 'error';
    $response['message'] = 'Tidak ada file yang di-upload atau ukuran file terlalu besar.';
    header('Content-Type: application/json');
    echo json_encode($response);
}
?>