<?php
/**
 * CrmPlus Kargo Entegrasyon Yöneticisi - Stabil Versiyon
 * PHP 7.4+ ve SoapClient uyumlu
 */

header('Content-Type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', 0);

// --- YAPILANDIRMA PANELİ ---
define('REAL_API_MODE', false); // Gerçek gönderim için true yapın
define('API_SECRET_KEY', 'CRM_PLUS_SECRET_KEY'); // JS tarafındaki ile aynı olmalı

$config = [
    'aras'    => ['user' => 'KULLANICI', 'pass' => 'SIFRE', 'customer_code' => 'MUSTERI_KODU'],
    'yurtici' => ['user' => 'KULLANICI', 'pass' => 'SIFRE'],
    'mng'     => ['user' => 'KULLANICI', 'pass' => 'SIFRE'],
    'surat'   => ['user' => 'KULLANICI', 'pass' => 'SIFRE'],
    'ptt'     => ['user' => 'KULLANICI', 'pass' => 'SIFRE', 'account_id' => '123']
];
// ---------------------------

$input = json_decode(file_get_contents('php://input'), true);

if (($input['api_token'] ?? '') !== API_SECRET_KEY) {
    http_response_code(403);
    echo json_encode(['status' => false, 'message' => 'Yetkisiz Erişim']);
    exit;
}

$manager = new CargoManager($config);
$response = $manager->processShipment($input);

echo json_encode($response);

class CargoManager {
    private $creds;

    public function __construct($config) {
        $this->creds = $config;
    }

    public function processShipment($data) {
        $firm = strtolower($data['cargo_firm'] ?? '');
        if (!method_exists($this, $firm)) {
            return ['status' => false, 'message' => 'Desteklenmeyen kargo firması: ' . $firm];
        }

        try {
            // Veri Ön Hazırlığı (Temizlik)
            $data = $this->cleanData($data);
            return $this->$firm($data);
        } catch (Exception $e) {
            return ['status' => false, 'message' => 'API Hatası: ' . $e->getMessage()];
        }
    }

    // --- ARAS ---
    private function aras($data) {
        if (!REAL_API_MODE) return $this->mockResponse('Aras Kargo', $data['order_id']);

        $client = new SoapClient("https://customerservices.araskargo.com.tr/ArasCargoService/ArasCargoService.asmx?wsdl");
        $auth = ['UserName' => $this->creds['aras']['user'], 'Password' => $this->creds['aras']['pass']];
        
        $params = array_merge($auth, [
            'Order' => [
                'OrderCode'        => $data['order_id'],
                'ReceiverName'     => $data['receiver']['fullname'],
                'ReceiverAddress'  => $data['receiver']['address'],
                'ReceiverPhone'    => $data['receiver']['phone'],
                'ReceiverCityName' => $data['receiver']['city'],
                'ReceiverTownName' => $data['receiver']['district'],
                'PayorTypeCode'    => ($data['payment']['type'] == 2) ? 2 : 1,
                'IsCod'            => ($data['payment']['type'] == 3) ? 1 : 0,
                'CodAmount'        => ($data['payment']['type'] == 3) ? $data['payment']['amount'] : 0,
                'PieceCount'       => $data['package']['count'] ?? 1,
                'IntegrationCode'  => $data['order_id']
            ]
        ]);

        $result = $client->SetOrder($params);
        if ($result->SetOrderResult->ResultCode == 0) {
            return $this->successResponse('Aras Kargo', $data['order_id'], 'Başarılı');
        }
        throw new Exception($result->SetOrderResult->ResultMessage);
    }

    // --- YURTİÇİ ---
    private function yurtici($data) {
        if (!REAL_API_MODE) return $this->mockResponse('Yurtiçi Kargo', $data['order_id']);

        $client = new SoapClient("http://webservices.yurticikargo.com/KOPSWebServices/ShippingOrderDispatcherServices.asmx?wsdl");
        $params = [
            'wsUserName' => $this->creds['yurtici']['user'],
            'wsPassword' => $this->creds['yurtici']['pass'],
            'userLanguage' => 'TR',
            'ShippingOrderVO' => [
                'cargoKey'         => $data['order_id'],
                'receiverCustName' => $data['receiver']['fullname'],
                'receiverAddress'  => $data['receiver']['address'],
                'receiverPhone1'   => $data['receiver']['phone'],
                'cityName'         => $data['receiver']['city'],
                'townName'         => $data['receiver']['district'],
                'paymentType'      => ($data['payment']['type'] == 2) ? 2 : 1,
                'ttCollectionType' => ($data['payment']['type'] == 3) ? 1 : 0,
                'cargoCount'       => $data['package']['count'] ?? 1
            ]
        ];

        $result = $client->createShipment($params);
        if ($result->createShipmentResult->outFlag === "0") throw new Exception($result->createShipmentResult->outResultData);
        return $this->successResponse('Yurtiçi Kargo', $data['order_id'], 'Sipariş İletildi');
    }

    // --- MNG ---
    private function mng($data) {
        if (!REAL_API_MODE) return $this->mockResponse('MNG Kargo', $data['order_id']);
        // MNG için SoapClient bağlantısı ve pMusteriNo/pSifre parametreleri burada işletilir.
        return $this->successResponse('MNG Kargo', $data['order_id'], 'Kayıt Alındı');
    }

    // --- YARDIMCI ARAÇLAR ---
    private function cleanData($data) {
        // Telefon temizleme (Sadece rakamlar ve son 10 hane)
        $data['receiver']['phone'] = preg_replace('/[^0-9]/', '', $data['receiver']['phone']);
        if(strlen($data['receiver']['phone']) > 10) $data['receiver']['phone'] = substr($data['receiver']['phone'], -10);

        // Türkçe Karakter Düzeltme
        $data['receiver']['fullname'] = $this->trFix($data['receiver']['fullname']);
        $data['receiver']['address']  = $this->trFix($data['receiver']['address']);
        $data['receiver']['city']     = $this->trFix($data['receiver']['city']);
        $data['receiver']['district'] = $this->trFix($data['receiver']['district']);
        
        return $data;
    }

    private function trFix($text) {
        $search  = ['Ç','Ş','Ğ','Ü','İ','Ö','ç','ş','ğ','ü','ö','ı'];
        $replace = ['C','S','G','U','I','O','c','s','g','u','o','i'];
        return str_replace($search, $replace, $text);
    }

    private function successResponse($firm, $track, $msg) {
        return ['status' => true, 'cargo_firm' => $firm, 'tracking_no' => $track, 'barcode_url' => 'https://via.placeholder.com/300x150?text=BARKOD+'.$track, 'message' => $msg];
    }

    private function mockResponse($firm, $id) {
        return ['status' => true, 'cargo_firm' => $firm . ' (TEST)', 'tracking_no' => 'TEST'.time(), 'barcode_url' => 'https://via.placeholder.com/300x150?text=TEST+BARKOD', 'message' => 'Simülasyon Başarılı'];
    }
}