<?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');
$projectId = (int)post('project_id', 0);

if ($action === 'list') {
    if (!$projectId) apiError('Project ID required.', 422);
    $stmt = $db->prepare("SELECT * FROM project_ftp WHERE project_id=? ORDER BY label");
    $stmt->execute([$projectId]);
    $rows = $stmt->fetchAll();
    foreach ($rows as &$r) {
        $r['password_plain'] = !empty($r['password_enc']) ? ewDecrypt($r['password_enc']) : '';
        unset($r['password_enc']);
    }
    apiSuccess(['connections' => $rows]);
}

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

$id   = (int)post('id', 0);
$host = trim(post('host', ''));
if (!$projectId) apiError('Project ID required.', 422);
if (!$host)      apiError('Host required.', 422);

$pwEnc = post('password_plain') ? ewEncrypt(post('password_plain')) : null;

if ($id) {
    $sql = "UPDATE project_ftp SET label=?,protocol=?,host=?,port=?,username=?,remote_path=?,notes=?" .
           ($pwEnc ? ",password_enc=?" : "") . " WHERE id=? AND project_id=?";
    $p = [post('label','Primary'), post('protocol','ftp'), $host, post('port',21), post('username'), post('remote_path'), post('notes')];
    if ($pwEnc) $p[] = $pwEnc;
    $p[] = $id; $p[] = $projectId;
    $db->prepare($sql)->execute($p);
    apiSuccess(['id' => $id], 'Updated.');
} else {
    $db->prepare("
        INSERT INTO project_ftp (project_id,label,protocol,host,port,username,password_enc,remote_path,notes,created_by)
        VALUES (?,?,?,?,?,?,?,?,?,?)
    ")->execute([$projectId, post('label','Primary'), post('protocol','ftp'), $host, post('port',21), post('username'), $pwEnc, post('remote_path'), post('notes'), $user['id']]);
    apiSuccess(['id' => (int)$db->lastInsertId()], 'FTP connection added.', 201);
}
