<?php
require('../config.php');
require '../../../vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\IOFactory;

if(isset($_POST['bonusIncentive_file'])){
    // valid extensions
    $extensions = array('xlsx', 'xls');

    $inputFileName = $_FILES['bonus_incentive_sample']['name'];
    $file = $_FILES['bonus_incentive_sample']; // ✅ define it
    $ext = pathinfo($inputFileName, PATHINFO_EXTENSION);
    $data = [];
    
    if ($ext === 'csv') {
        // Parse CSV
        if (($handle = fopen($file['tmp_name'], "r")) !== FALSE) {
            while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
                $data[] = $row;
            }
            fclose($handle);
        }
    } elseif ($ext === 'xlsx') {
        // Parse XLSX
        $spreadsheet = IOFactory::load($file['tmp_name']);
        $sheet = $spreadsheet->getActiveSheet();
        $rows = $sheet->toArray();
        foreach ($rows as $row) {
            $data[] = $row;
        }
    }

    // Example: assume first row is headers
    $headers = array_map('trim', $data[0]);
    unset($data[0]);
    
    foreach ($data as $row) {

        $employee_id = mysqli_real_escape_string($db, $row[0]);
        $bonus = mysqli_real_escape_string($db, preg_replace('/\D/', '', $row[1]));
        $incentive = mysqli_real_escape_string($db, preg_replace('/\D/', '', $row[2]));
        $bonusIncentive_date = mysqli_real_escape_string($db, $row[3]);

        $exist = mysqli_num_rows(mysqli_query($db, "SELECT * from employee_bonusIncentive where employee_id='$employee_id' and date='$bonusIncentive_date' "));
        if ($exist == 0) {
            $q = mysqli_query($db, "INSERT INTO `employee_bonusIncentive` (`employee_id`, `bonus`, `incentive`, `date`) VALUES('$employee_id', '$bonus', '$incentive', '$bonusIncentive_date') ");
        } else {
            $q = mysqli_query($db, "UPDATE `employee_bonusIncentive` SET  `bonus`='$bonus', `incentive`='$incentive' WHERE `employee_id`='$employee_id' AND `date`='$bonusIncentive_date' ");
        }
    }
    echo json_encode(['status' => 200, 'message' => 'File processed and data inserted.']);
}





