prepare( "SELECT status, doc_type, `log` FROM td_invoice WHERE company_id = :company_id AND id = :id" ); $sth->execute([':company_id' => $company_id, ':id' => $id]); $row = $sth->fetch(PDO::FETCH_ASSOC); if (!$row) throw new Exception("Invoice not found."); if ($row['doc_type'] !== 'invoice') throw new Exception("Only invoices can be updated this way."); $current = (int)$row['status']; if ($current === 4) throw new Exception("Invoice is already void."); if ($current === 0) throw new Exception("Issue the invoice before changing payment status."); $log = json_decode($row['log'] ?? '[]', true) ?: []; $log[] = array_merge($logging, [ 'action' => 'update_status', 'status' => $status, 'previous_status' => $current, ]); $pdo->prepare( "UPDATE td_invoice SET status = :status, `log` = :log WHERE id = :id AND company_id = :company_id" )->execute([ ':status' => $status, ':log' => json_encode($log), ':id' => $id, ':company_id' => $company_id, ]); }); $answer['success'] = 1; $answer['message'] = 'Invoice status updated.'; } catch (PDOException $e) { $answer['message'] = 'Database error, please try again.'; http_response_code(500); } catch (Exception $e) { $answer['message'] = $e->getMessage(); http_response_code(400); } exit(json_encode($answer)); ?>