<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Mycase_proxy extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        // load helpers or libraries if needed
    }

    public function create_client()
    {
        // get incoming JSON from fetch
        $input = file_get_contents('php://input');
        $req_body = json_decode($input, true);

        // optionally validate req_body or merge with dummy data
        // For demo — we’ll ignore req_body and use dummy data
        $payload = [
            "email" => "dummy@example.com",
            "first_name" => "John",
            "middle_name" => "M",
            "last_name" => "Doe",
            "address" => [
                "address1" => "123 Main St",
                "address2" => "",
                "city" => "Springfield",
                "state" => "IL",
                "zip_code" => "12345",
                "country" => "USA"
            ],
        ];

        $url = "https://external-integrations.mycase.com/v1/clients";
        $access_token = "YOUR_ACCESS_TOKEN_HERE";

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Content-Type: application/json",
            "Authorization: Bearer {$access_token}"
        ]);

        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($response === false) {
            $error = curl_error($ch);
            curl_close($ch);
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode([
                    "success" => false,
                    "error" => $error
                ]));
            return;
        }
        curl_close($ch);

        // return MyCase response to frontend
        $this->output
            ->set_content_type('application/json')
            ->set_output($response);
    }
}
