<?php
/**
 * ZATCA Phase 2 API Endpoint
 * Simple REST API for invoice generation and reporting
 */

header('Content-Type: application/json; charset=utf-8');
date_default_timezone_set('Asia/Riyadh');

require_once 'invoice_processor.php';

class ZATCAAPI {
    private $processor;
    
    public function __construct() {
        $this->processor = new ZATCAInvoiceProcessor();
    }
    
    /**
     * Handle API request
     */
    public function handleRequest() {
        try {
            // Get request method
            $method = $_SERVER['REQUEST_METHOD'];
            
            if ($method !== 'POST') {
                return $this->errorResponse('Only POST method is allowed', 405);
            }
            
            // Get POST data
            $input = file_get_contents('php://input');
            $data = json_decode($input, true);
            
            if (json_last_error() !== JSON_ERROR_NONE) {
                return $this->errorResponse('Invalid JSON input', 400);
            }
            
            // Validate required fields
            $validation = $this->validateInvoiceData($data);
            if (!$validation['valid']) {
                return $this->errorResponse($validation['message'], 400);
            }
            
            // Process invoice
            $result = $this->processor->processInvoice($data);
            
            if ($result['success']) {
                return $this->successResponse($result);
            } else {
                return $this->errorResponse('Invoice processing failed', 422, $result);
            }
            
        } catch (Exception $e) {
            return $this->errorResponse($e->getMessage(), 500);
        }
    }
    
    /**
     * Validate invoice data
     */
    private function validateInvoiceData($data) {
        $required = [
            'invoice_number',
            'issue_date',
            'supplier',
            'customer',
            'items',
            'totals',
            'payment_by',
            'invoice_type'
        ];
        
        foreach ($required as $field) {
            if (!isset($data[$field])) {
                return [
                    'valid' => false,
                    'message' => "Missing required field: $field"
                ];
            }
        }
        
        // Validate supplier
        if (!isset($data['supplier']['name']) || !isset($data['supplier']['vat_number'])) {
            return [
                'valid' => false,
                'message' => 'Missing supplier name or VAT number'
            ];
        }
        
        // Validate items
        if (empty($data['items']) || !is_array($data['items'])) {
            return [
                'valid' => false,
                'message' => 'Invoice must have at least one item'
            ];
        }
        
        // Validate totals
        if (!isset($data['totals']['net_amount']) || 
            !isset($data['totals']['vat_total']) || 
            !isset($data['totals']['grand_total'])) {
            return [
                'valid' => false,
                'message' => 'Missing totals information'
            ];
        }
        
        return ['valid' => true];
    }
    
    /**
     * Success response
     */
    private function successResponse($data) {
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'message' => 'Invoice processed successfully',
            'data' => [
                'invoice_number' => $data['invoice_number'],
                'uuid' => $data['uuid'],
                'hash' => $data['hash'],
                'folder' => $data['folder'],
                'zatca_status' => $data['result']['reporting_status'],
                'warnings' => $data['result']['warnings'] ?? []
            ]
        ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    }
    
    /**
     * Error response
     */
    private function errorResponse($message, $code = 400, $details = null) {
        http_response_code($code);
        
        $response = [
            'success' => false,
            'error' => $message
        ];
        
        if ($details) {
            $response['details'] = $details;
        }
        
        echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    }
}

// Run API
$api = new ZATCAAPI();
$api->handleRequest();
?>