<?php
ob_start();
include '../includes/session.php';
include '../includes/constants.php';
include '../includes/functions.php';
include '../includes/allstripslashes.php';

// database connection
$partners = new partners;
$mysqli = $partners->connection($host, $user, $pass, $db);

// Constants
$uploadField = 'txt_file';
$targetFile = "ip_sql.sql";
$returnUrl = "index.php?Act=ip_country_update";

// Remove existing file
if (file_exists($targetFile)) {
    unlink($targetFile);
}

// Validate file upload
if (!isset($_FILES[$uploadField]) || $_FILES[$uploadField]['error'] !== UPLOAD_ERR_OK) {
    $msg = urlencode("Please choose a valid SQL file to upload.");
    header("Location: {$returnUrl}&msg={$msg}");
    exit;
}

$fileName = $_FILES[$uploadField]['name'];
$fileTmpName = $_FILES[$uploadField]['tmp_name'];
$fileSize = $_FILES[$uploadField]['size'];
$fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

// Check file extension
if ($fileExt !== 'sql') {
    $msg = urlencode("Only .sql files are allowed.");
    header("Location: {$returnUrl}&msg={$msg}");
    exit;
}

// Optional: MIME type check
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->file($fileTmpName);
if (strpos($mimeType, 'text') === false && strpos($mimeType, 'sql') === false) {
    $msg = urlencode("Invalid file type. Please upload a valid SQL file.");
    header("Location: {$returnUrl}&msg={$msg}");
    exit;
}

// Move uploaded file securely
if (!move_uploaded_file($fileTmpName, $targetFile)) {
    $msg = urlencode("Failed to save the uploaded file.");
    header("Location: {$returnUrl}&msg={$msg}");
    exit;
}

// Read SQL content
$sqlContent = file_get_contents($targetFile);
if ($sqlContent === false) {
    $msg = urlencode("Could not read SQL file.");
    header("Location: {$returnUrl}&msg={$msg}");
    exit;
}

// Split into individual lines
$lines = explode("\n", $sqlContent);
foreach ($lines as $line) {
    $line = trim($line);
    if (
        stripos($line, "insert into `partners_countryflag`") === 0 ||
        stripos($line, "insert into partners_countryflag") === 0
    ) {
        if (!$mysqli->query($line)) {
            $msg = urlencode("Error executing SQL: " . $mysqli->error);
            header("Location: {$returnUrl}&msg={$msg}");
            exit;
        }
    } else {
        $msg = urlencode("Invalid SQL file. It must contain only INSERTs into partners_countryflag.");
        header("Location: {$returnUrl}&msg={$msg}");
        exit;
    }
}

// Cleanup uploaded file
if (file_exists($targetFile)) {
    unlink($targetFile);
}

// Success
$msg = urlencode("Successfully Updated the Database");
header("Location: {$returnUrl}&msg={$msg}");
exit;
?>
