<?php

require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;

$host = 'localhost';
$db   = 'kufgkmxh_loan';
$user = 'kufgkmxh_ussd';
$pass = 'B80P4bGqN7NUyk';

$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) die("DB connection failed");

if (!isset($_FILES['file'])) {
    die('No file uploaded.');
}

$uploadDir = __DIR__ . '/uploads/';
if (!is_dir($uploadDir)) mkdir($uploadDir);

$filename = basename($_FILES['file']['name']);
$targetPath = $uploadDir . $filename;

if (!move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)) {
    die('Failed to move uploaded file.');
}

$ext = pathinfo($filename, PATHINFO_EXTENSION);

$chunkSize = 1000;

if ($ext === 'csv') {
    $handle = fopen($targetPath, 'r');
    $header = fgetcsv($handle);

    $buffer = [];
    while (($row = fgetcsv($handle)) !== false) {
        $buffer[] = $row;
        if (count($buffer) >= $chunkSize) {
            insertBatch($conn, $buffer);
            $buffer = [];
        }
    }
    if (!empty($buffer)) {
        insertBatch($conn, $buffer);
    }
    fclose($handle);
} else {
    $spreadsheet = IOFactory::load($targetPath);
    $sheet = $spreadsheet->getActiveSheet();
    $rows = $sheet->toArray();
    unset($rows[0]);

    $buffer = [];
    foreach ($rows as $row) {
        $buffer[] = $row;
        if (count($buffer) >= $chunkSize) {
            insertBatch($conn, $buffer);
            $buffer = [];
        }
    }
    if (!empty($buffer)) {
        insertBatch($conn, $buffer);
    }
    unlink($targetPath);
}

function insertBatch($conn, $rows) {
    $stmt = $conn->prepare("INSERT INTO contacts (phone_number, name) VALUES (?, ?)");
    foreach ($rows as $row) {
        $phone = sanitize($row[0]?? "");
        $name = $row[1]??"";
        $stmt->bind_param("ss", $phone, $name);
        $stmt->execute();
    }
    $stmt->close();
}

function sanitize($phoneNumber){
     if (strlen($phoneNumber) == 10 && substr($phoneNumber, 0, 1) == "0") {
            return "254" . substr($phoneNumber, 1);
        }
         if (strlen($phoneNumber) == 9) {
            return "254" . $phoneNumber;
        }
        if (strlen($phoneNumber) == 12 && substr($phoneNumber, 0, 3) == "254") {
            return $phoneNumber;
        }
        
         if (!is_numeric($phoneNumber)) {
            return null; // Invalid input
        }
        if($phoneNumber==""){
            return "";
        }
}

?>

<!DOCTYPE html>
<html>
<head>
  <title>Success</title>
</head>
<body style="text-align: center; font-family: sans-serif; padding-top: 50px;">
  <h2 style="color: green;">🎉 Import Successful!</h2>
  <a href="index.php" style="text-decoration: none; font-size: 18px;">⬅️ Back to Upload</a>
</body>
</html>
