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

$action   = post('action', 'list');
$clientId = (int)post('client_id', 0);

try {
    if ($action === 'list') {
        if (!$clientId) apiError('Client ID required.', 422);
        $stmt = $db->prepare("
            SELECT p.*, u.full_name AS created_by_name
            FROM client_passwords p
            LEFT JOIN users u ON u.id = p.created_by
            WHERE p.client_id = ?
            ORDER BY p.category, p.label
        ");
        $stmt->execute([$clientId]);
        $rows = $stmt->fetchAll();
        foreach ($rows as &$r) {
            $r['password_plain'] = !empty($r['password_enc']) ? ewDecrypt($r['password_enc']) : '';
            unset($r['password_enc']);
        }
        apiSuccess(['passwords' => $rows]);
    }

    if ($action === 'delete') {
        $id = (int)post('id', 0);
        $db->prepare("DELETE FROM client_passwords WHERE id=? AND client_id=?")->execute([$id, $clientId]);
        apiSuccess([], 'Deleted.');
    }

    $id    = (int)post('id', 0);
    $label = trim(post('label', ''));
    $pw    = post('password_plain', '');
    if (!$clientId) apiError('Client ID required.', 422);
    if (!$label)    apiError('Label required.', 422);
    if (!$pw && !$id) apiError('Password required.', 422);

    $pwEnc = $pw ? ewEncrypt($pw) : null;

    if ($id) {
        $sql = "UPDATE client_passwords SET label=?,category=?,url=?,username=?,notes=?" .
               ($pwEnc ? ",password_enc=?" : "") . " WHERE id=? AND client_id=?";
        $p = [post('label'), post('category','other'), post('url'), post('username'), post('notes')];
        if ($pwEnc) $p[] = $pwEnc;
        $p[] = $id; $p[] = $clientId;
        $db->prepare($sql)->execute($p);
        apiSuccess(['id' => $id], 'Updated.');
    } else {
        $db->prepare("
            INSERT INTO client_passwords (client_id,label,category,url,username,password_enc,notes,created_by)
            VALUES (?,?,?,?,?,?,?,?)
        ")->execute([$clientId, $label, post('category','other'), post('url'), post('username'), $pwEnc, post('notes'), $user['id']]);
        apiSuccess(['id' => (int)$db->lastInsertId()], 'Password saved.', 201);
    }
} catch (Exception $e) {
    apiError('Database error: ' . $e->getMessage(), 500);
}
