<?php

//include '../config/db.php';
require_once __DIR__ . '/../config/db.php';

if(isset($_FILES['csv_file']))
{
    $file =
    fopen(
        $_FILES['csv_file']['tmp_name'],
        "r"
    );

    $count = 0;

    fgetcsv($file);

    while(($row =
    fgetcsv($file,1000,","))
    !== FALSE)
    {

        $census_no = trim($row[0]);
        $district = trim($row[1]);
        $zone = trim($row[2]);
        $division = trim($row[3]);
        $school = trim($row[4]);
        $category = trim($row[5]);
        $type = trim($row[6]);

        if(empty($census_no))
        {
            continue;
        }

        $sql =
        "INSERT INTO schools
        (
        census_no,
        district,
        zone_name,
        division_name,
        school_name,
        school_category,
        school_type
        )
        VALUES
        (?,?,?,?,?,?,?)
        ON DUPLICATE KEY UPDATE

        district=VALUES(district),
        zone_name=VALUES(zone_name),
        division_name=VALUES(division_name),
        school_name=VALUES(school_name),
        school_category=VALUES(school_category),
        school_type=VALUES(school_type)
        ";

        $stmt =
        mysqli_prepare($conn,$sql);

        mysqli_stmt_bind_param(
        $stmt,
        "sssssss",
        $census_no,
        $district,
        $zone,
        $division,
        $school,
        $category,
        $type
        );

        mysqli_stmt_execute($stmt);

        $count++;
    }

    fclose($file);

    echo "
    <script>
    alert('$count School Records Imported Successfully');
    window.location='manage_schools.php';
    </script>
    ";
}
?>