<?php
require_once __DIR__ . '/../_pdo_db_connect.php';
require_once __DIR__ . '/../_response.php';
require_once __DIR__ . '/../_middleware/auth_check.php';
$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()]);
}
