<?php
require_once __DIR__.'/../_pdo_db_connect.php';
require_once __DIR__.'/../middleware/auth_check.php';
require_once __DIR__.'/../../Controllers/CustomerController.php';

$auth = new AuthCheck();
$user = $auth->requireAuth();

$data = json_decode(file_get_contents('php://input'), true);
$controller = new CustomerController($pdo);
$result = $controller->createOrUpdate($data, $user);

echo json_encode($result);

$payload = require_auth();
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) json_res(['error'=>'invalid_input'],400);
$pdo = get_db();
if (!empty($input['id'])){
    $stmt = $pdo->prepare('UPDATE sd_customers SET name=?,phone=?,email=?,customer_status=?,meta=? WHERE id=?');
    $stmt->execute([$input['name'],$input['phone'],$input['email'],$input['customer_status'],json_encode($input['meta'] ?? []), $input['id']]);
    json_res(['status'=>'updated']);
}else{
    $stmt = $pdo->prepare('INSERT INTO sd_customers(name,phone,email,customer_status,meta,created_at) VALUES(?,?,?,?,?,NOW())');
    $stmt->execute([$input['name'],$input['phone'],$input['email'],$input['customer_status'],json_encode($input['meta'] ?? [])]);
    json_res(['status'=>'created','id'=>$pdo->lastInsertId()]);
}

?>