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

$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
    die("Database connection failed: " . $mysqli->connect_error);
}

$filename = "ip_sql.sql";

// Remove existing file
if (file_exists($filename)) unlink($filename);

// Validate uploaded file
if (!isset($_FILES['txt_file']) || $_FILES['txt_file']['error'] !== UPLOAD_ERR_OK) {
    header("Location: index.php?Act=ip_country_update&msg=" . urlencode("Please choose an SQL file"));
    exit;
}

$file = $_FILES['txt_file'];
$file_ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if ($file_ext !== 'sql') {
    header("Location: index.php?Act=ip_country_update&msg=" . urlencode("Please choose an SQL file"));
    exit;
}

// Move uploaded file
if (!move_uploaded_file($file['tmp_name'], $filename)) {
    header("Location: index.php?Act=ip_country_update&msg=" . urlencode("File upload failed"));
    exit;
}

// Read file and execute queries
$content = file_get_contents($filename);
$lines = explode("\n", $content);

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)) {
            header("Location: index.php?Act=ip_country_update&msg=" . urlencode("SQL error: " . $mysqli->error));
            exit;
        }
    } else {
        header("Location: index.php?Act=ip_country_update&msg=" . urlencode("Invalid SQL file"));
        exit;
    }
}

unlink($filename);
header("Location: index.php?Act=ip_country_update&msg=" . urlencode("Successfully Updated the Database"));
exit;
?>
