<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'includes/config.php';
require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\IOFactory;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    try {
        $file = $_FILES['file'];
        
        // Validasi file
        if ($file['error'] !== UPLOAD_ERR_OK) {
            throw new Exception('File upload error code: ' . $file['error']);
        }
        
        $allowedTypes = [
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // xlsx
            'application/vnd.ms-excel', // xls
            'application/octet-stream' // Untuk beberapa sistem yang mengirim dengan mime type ini
        ];
        
        if (!in_array($file['type'], $allowedTypes) && !empty($file['type'])) {
            throw new Exception('Invalid file type. Please upload Excel file (.xlsx or .xls)');
        }

        // Baca file Excel
        $spreadsheet = IOFactory::load($file['tmp_name']);
        $worksheet = $spreadsheet->getActiveSheet();
        $rows = $worksheet->toArray();
        
        // Debug info
        error_log("Total rows read: " . count($rows));
        
        // Skip header row if exists
        $headerRow = $rows[0];
        if (stripos($headerRow[0], 'target') !== false || stripos($headerRow[0], 'number') !== false) {
            array_shift($rows);
        }
        
        // Prepare insert statement
        $stmt = $db->prepare("INSERT INTO target_numbers (phone_number, status) VALUES (?, '-')");
        
        // Begin transaction
        $db->beginTransaction();
        
        $successCount = 0;
        $errors = [];
        
        foreach ($rows as $index => $row) {
            // Debug info
            error_log("Processing row " . ($index + 1) . ": " . print_r($row, true));
            
            if (empty($row[0])) {
                error_log("Empty row found at index " . ($index + 1));
                continue;
            }
            
            // Bersihkan nomor telepon dari karakter non-angka
            $phoneNumber = preg_replace('/[^0-9]/', '', trim($row[0]));
            
            // Jika nomor dimulai dengan 0, ganti dengan +62
            if (substr($phoneNumber, 0, 1) === '0') {
                $phoneNumber = '+62' . substr($phoneNumber, 1);
            }
            // Jika nomor dimulai dengan 62, tambahkan +
            else if (substr($phoneNumber, 0, 2) === '62') {
                $phoneNumber = '+' . $phoneNumber;
            }
            // Jika nomor tidak dimulai dengan 0 atau 62, tambahkan +62
            else {
                $phoneNumber = '+62' . $phoneNumber;
            }
            
            // Debug info
            error_log("Formatted phone number: " . $phoneNumber);
            
            // Validasi nomor telepon (panjang 13-15 karakter termasuk +62)
            if (strlen($phoneNumber) < 13 || strlen($phoneNumber) > 15) {
                $errors[] = "Invalid phone number at row " . ($index + 2) . ": " . $row[0];
                error_log("Invalid phone number length: " . strlen($phoneNumber));
                continue;
            }
            
            try {
                $stmt->execute([$phoneNumber]);
                $successCount++;
            } catch (PDOException $e) {
                if ($e->getCode() == 23000) { // Duplicate entry
                    $errors[] = "Duplicate phone number at row " . ($index + 2) . ": " . $phoneNumber;
                } else {
                    throw $e;
                }
            }
        }
        
        // Commit transaction
        $db->commit();
        
        $response = [
            'success' => true,
            'message' => "Successfully imported {$successCount} numbers" . (count($errors) > 0 ? " with " . count($errors) . " errors" : ""),
            'errors' => $errors
        ];
        
    } catch (Exception $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        
        error_log("Import error: " . $e->getMessage());
        error_log("Stack trace: " . $e->getTraceAsString());
        
        $response = [
            'success' => false,
            'message' => $e->getMessage()
        ];
    }
    
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
} else {
    // Jika bukan POST request atau tidak ada file
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'No file uploaded or invalid request method'
    ]);
    exit;
} 