<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
$user = requireAuth();
$db   = getDB();

$id       = (int)post('id', 0);
$clientId = (int)post('client_id', 0);
$name     = trim(post('name', ''));

if (!$clientId) apiError('Client ID required.', 422);
if (!$name)     apiError('Asset name required.', 422);

try {
    if ($id) {
        $db->prepare("
            UPDATE client_assets
            SET name=?,asset_type=?,brand=?,model=?,serial_number=?,
                purchase_date=?,warranty_expiry=?,location_desc=?,notes=?,status=?
            WHERE id=? AND client_id=?
        ")->execute([
            $name, post('asset_type','other'), post('brand'), post('model'), post('serial_number'),
            post('purchase_date') ?: null, post('warranty_expiry') ?: null,
            post('location_desc'), post('notes'), post('status','active'),
            $id, $clientId
        ]);
        apiSuccess(['id' => $id], 'Asset updated.');
    } else {
        $db->prepare("
            INSERT INTO client_assets
                (client_id,name,asset_type,brand,model,serial_number,
                 purchase_date,warranty_expiry,location_desc,notes,status,created_by)
            VALUES (?,?,?,?,?,?,?,?,?,?,?,?)
        ")->execute([
            $clientId, $name, post('asset_type','other'), post('brand'), post('model'), post('serial_number'),
            post('purchase_date') ?: null, post('warranty_expiry') ?: null,
            post('location_desc'), post('notes'), post('status','active'),
            $user['id']
        ]);
        apiSuccess(['id' => (int)$db->lastInsertId()], 'Asset added.', 201);
    }
} catch (Exception $e) {
    apiError('Database error: ' . $e->getMessage(), 500);
}
