<?php
require 'vendor/autoload.php';

use App\ZohoService;
use App\PdfGenerator;
use App\EmailService;

// Load config
$config = require 'config/config.php';

// Get POST data and log it
$input = file_get_contents('php://input');
error_log('Webhook received: ' . $input);

try {
    // Parse URL-encoded data
    parse_str($input, $data);
    
    // Log raw data setelah parsing
    error_log('Parsed data: ' . print_r($data, true));
    // Decode JSON line items and email list
    $data['line_items'] = json_decode(urldecode($data['line_items']), true);
    $emailList = json_decode(urldecode($data['email']), true);     

    // Format invoice data
    $invoiceData = [
        'invoice_id' => $data['invoice_id'],
        'invoice_number' => $data['invoice_number'],
        'date' => $data['date'],
        'customer_name' => urldecode($data['customer_name']),
        'customer_address' => [
            'address' => urldecode($data['address']),
            'city' => urldecode($data['city']),
            'state' => urldecode($data['state']),
            'zip' => urldecode($data['zip']),
            'country' => urldecode($data['country'])
        ],
        'total' => $data['total'],
        'line_items' => $data['line_items'],
        'company_name' => urldecode($data['org_name']),
        'company_address' => [
            'address1' => urldecode($data['org_address1']),
            'address2' => urldecode($data['org_address2']),
            'city' => urldecode($data['org_city']),
            'state' => urldecode($data['org_state']),
            'zip' => urldecode($data['org_zip'])
        ],
        'terms' => urlencode($data['terms']),
        'due_date' => urlencode($data['due_date']),
        'status' => urlencode($data['status']),
        'notes' => urlencode($data['notes']),
        'po' => urlencode($data['po']),
        'quote' => urlencode($data['quote']),
        'term_condition' => urlencode($data['term_condition'])
    ];
    // Log formatted invoice data
    error_log('Formatted invoice data: ' . print_r($invoiceData, true));

    // Initialize services
    $pdfGenerator = new PdfGenerator();
    $emailService = new EmailService($config);

    // Decode email list dengan benar
    $emailData = urldecode($data['email']);
    $emailList = [['email' => $emailData]]; // Ubah menjadi array yang sesuai

    // Generate PDF
    $pdfPath = $pdfGenerator->generatePdf($invoiceData);

    // Send to recipient
    $result = null;
    foreach ($emailList as $emailData) {
        $result = $emailService->sendInvoice(
            $emailData['email'],
            $pdfPath,
            $data['invoice_number']
        );
        error_log('Email sent to: ' . $emailData['email']);
    }

    // Log the result
    error_log('Process result: ' . json_encode($result));

    // Return success response
    echo json_encode([
        'status' => 'success',
        'message' => 'Invoice processed successfully'
    ]);

} catch (Exception $e) {
    $result = ['status' => 'error', 'message' => $e->getMessage()];
    error_log('Process result: ' . json_encode($result));
    
    http_response_code(500);
    echo json_encode($result);
}

