<?php
/**
 * IMPORT PROCESS - PIUTANG DASHBOARD
 * FIXED VERSION
 */

header('Content-Type: application/json');

// ===== LOAD AUTOLOAD =====
$autoloadPaths = [
    __DIR__ . '/../../vendor/autoload.php',
    __DIR__ . '/../../../vendor/autoload.php',
];

$loaded = false;
foreach ($autoloadPaths as $path) {
    if (file_exists($path)) {
        require_once $path;
        $loaded = true;
        break;
    }
}

if (!$loaded) {
    die(json_encode(['success' => false, 'error' => 'Autoload not found']));
}

use PhpOffice\PhpSpreadsheet\IOFactory;

require_once 'data_config.php';

// Handle file upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['excel_file'])) {
    $period = isset($_POST['period']) ? trim($_POST['period']) : '';
    
    if (empty($period)) {
        die(json_encode(['success' => false, 'error' => 'Period is required']));
    }
    
    $file = $_FILES['excel_file'];
    
    if ($file['error'] !== UPLOAD_ERR_OK) {
        die(json_encode(['success' => false, 'error' => 'Upload error: ' . $file['error']]));
    }
    
    if ($file['size'] > 5 * 1024 * 1024) {
        die(json_encode(['success' => false, 'error' => 'File too large (max 5MB)']));
    }
    
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    
    if (!in_array($ext, ['xlsx', 'xls', 'csv'])) {
        die(json_encode(['success' => false, 'error' => 'Invalid format. Use xlsx, xls, or csv']));
    }
    
    try {
        if ($ext === 'csv') {
            $data = importFromCSV($file['tmp_name']);
        } else {
            if (!class_exists('PhpOffice\PhpSpreadsheet\IOFactory')) {
                die(json_encode(['success' => false, 'error' => 'PhpSpreadsheet not available']));
            }
            $data = importFromExcel($file['tmp_name']);
        }
        
        if (empty($data)) {
            throw new Exception('No valid data found');
        }
        
        if (saveDataToFile($period, $data)) {
            echo json_encode([
                'success' => true,
                'message' => 'Import successful',
                'count' => count($data)
            ]);
        } else {
            throw new Exception('Failed to save data');
        }
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

echo json_encode(['success' => false, 'error' => 'Invalid request']);
exit;

function importFromExcel($filepath) {
    try {
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($filepath);
        $sheet = $spreadsheet->getActiveSheet();
        $rows = $sheet->toArray();
        return parseImportData($rows);
    } catch (Exception $e) {
        throw new Exception('Excel read failed: ' . $e->getMessage());
    }
}

function importFromCSV($filepath) {
    $rows = [];
    if (($h = fopen($filepath, 'r')) !== FALSE) {
        while (($d = fgetcsv($h, 10000, ',')) !== FALSE) {
            $rows[] = $d;
        }
        fclose($h);
    }
    return parseImportData($rows);
}

function parseImportData($rows) {
    if (empty($rows)) return [];
    
    $data = [];
    $current = null;
    $start = 0;
    
    for ($i = 0; $i < count($rows); $i++) {
        if (isset($rows[$i][0]) && trim($rows[$i][0]) === 'No') {
            $start = $i + 1;
            break;
        }
    }
    
    for ($i = $start; $i < count($rows); $i++) {
        $row = $rows[$i];
        
        if (empty($row[0]) && empty($row[1])) continue;
        if (isset($row[0]) && strtoupper(trim($row[0])) === 'TOTAL') break;
        
        if (!empty($row[0]) && is_numeric(trim($row[0]))) {
            if ($current !== null) $data[] = $current;
            
            $current = [
                'sekolah' => trim($row[1] ?? ''),
                'target' => cleanNumber($row[2] ?? 0),
                'capaian' => cleanNumber($row[3] ?? 0),
                'jenis' => []
            ];
        } else if (isset($row[1]) && (strpos($row[1], '→') !== false || strpos($row[1], '->') !== false)) {
            if ($current !== null) {
                $jenis = trim(str_replace(['→', '->', ' '], '', $row[1]));
                if (!empty($jenis)) {
                    $current['jenis'][] = [
                        'jenis' => $jenis,
                        'target' => cleanNumber($row[2] ?? 0),
                        'capaian' => cleanNumber($row[3] ?? 0)
                    ];
                }
            }
        }
    }
    
    if ($current !== null) $data[] = $current;
    return $data;
}

function cleanNumber($val) {
    if (is_numeric($val)) return (int)$val;
    $clean = preg_replace('/[^\d]/', '', str_replace([',', '.'], '', (string)$val));
    return !empty($clean) ? (int)$clean : 0;
}