<?php
namespace App\Services;

class MpesaParser
{
    /**
     * Parse Safaricom M‑Pesa statement CSV
     * Expected columns: Receipt No., Completion Date, Details, Transaction Status, Paid In, Withdrawn, Balance, Transaction Type, Other Party
     * 
     * @param string $filePath Full path to uploaded CSV file
     * @return array Array of transactions
     */
    public function parse($filePath)
    {
        $transactions = [];
        
        if (!file_exists($filePath)) {
            error_log("MpesaParser: File not found - " . $filePath);
            return [];
        }
        
        if (($handle = fopen($filePath, "r")) !== false) {
            // Skip header row
            $headers = fgetcsv($handle);
            
            // Optional: Detect CSV format (Safaricom uses specific columns)
            $rowCount = 0;
            while (($data = fgetcsv($handle)) !== false) {
                $rowCount++;
                if (count($data) < 9) {
                    continue; // Skip malformed rows
                }
                
                $transactions[] = [
                    'receipt_number'     => trim($data[0]),
                    'completion_date'    => $this->parseDate(trim($data[1])),
                    'details'            => trim($data[2]),
                    'transaction_status' => trim($data[3]),
                    'paid_in'            => $this->parseAmount(trim($data[4])),
                    'withdrawn'          => $this->parseAmount(trim($data[5])),
                    'balance'            => $this->parseAmount(trim($data[6])),
                    'transaction_type'   => trim($data[7]),
                    'other_party'        => trim($data[8]),
                ];
            }
            fclose($handle);
        }
        
        return $transactions;
    }
    
    /**
     * Parse M‑Pesa date format: "DD/MM/YYYY HH:MM:SS"
     * 
     * @param string $value
     * @return string|null MySQL datetime format or null
     */
    private function parseDate($value)
    {
        if (empty($value)) {
            return null;
        }
        
        // Try different formats (Safaricom sometimes changes)
        $formats = [
            'd/m/Y H:i:s',
            'd/m/Y H:i',
            'Y-m-d H:i:s',
            'Y-m-d'
        ];
        
        foreach ($formats as $format) {
            $dt = \DateTime::createFromFormat($format, $value);
            if ($dt !== false) {
                return $dt->format('Y-m-d H:i:s');
            }
        }
        
        // Fallback: try strtotime
        $timestamp = strtotime($value);
        if ($timestamp) {
            return date('Y-m-d H:i:s', $timestamp);
        }
        
        return null;
    }
    
    /**
     * Parse amount string (remove commas, convert to float)
     * 
     * @param string $value
     * @return float
     */
    private function parseAmount($value)
    {
        if (empty($value) || trim($value) === '') {
            return 0.00;
        }
        
        // Remove commas and any currency symbols
        $clean = preg_replace('/[^0-9\.\-]/', '', $value);
        return floatval($clean);
    }
}