<?php
/**
 * Update Company Endpoint
 * POST /v1/companies/update
 */

use App\Core\Database;
use App\Core\Encryption;
use App\Core\AuditLogger;
use App\Middleware\AuthMiddleware;
use App\Middleware\RoleMiddleware;

$decoded = RoleMiddleware::require(['super_admin', 'admin']);

$data = input();
$id = $data['id'] ?? null;
if (!$id) json_error('معرّف الشركة مطلوب', 422);

$db = Database::getInstance();
$tenantId = $decoded['tenant_id'];
$role = $decoded['role'];

// Verify access
$query = $role === 'super_admin'
    ? "SELECT * FROM companies WHERE id = ?"
    : "SELECT * FROM companies WHERE id = ? AND tenant_id = ?";
$params = $role === 'super_admin' ? [$id] : [$id, $tenantId];
$stmt = $db->prepare($query);
$stmt->execute($params);
$company = $stmt->fetch();

if (!$company) json_error('الشركة غير موجودة', 404);

$fields = [];
$values = [];

if (isset($data['name'])) {
    $fields[] = 'name = ?';
    $values[] = Encryption::encrypt($data['name']);
}
if (isset($data['name_en'])) {
    $fields[] = 'name_en = ?';
    $values[] = !empty($data['name_en']) ? Encryption::encrypt($data['name_en']) : null;
}
if (isset($data['tax_identification_number'])) {
    $fields[] = 'tax_identification_number = ?';
    $values[] = $data['tax_identification_number'];
}
if (isset($data['commercial_registration_number'])) {
    $fields[] = 'commercial_registration_number = ?';
    $values[] = $data['commercial_registration_number'];
}
if (isset($data['address'])) {
    $fields[] = 'address = ?';
    $values[] = $data['address'];
}
if (isset($data['city'])) {
    $fields[] = 'city = ?';
    $values[] = $data['city'];
}
if (isset($data['contact_email'])) {
    $fields[] = 'contact_email = ?';
    $values[] = $data['contact_email'];
}
if (isset($data['contact_phone'])) {
    $fields[] = 'contact_phone = ?';
    $values[] = $data['contact_phone'];
}

if (empty($fields)) json_error('لا توجد بيانات للتحديث', 422);

$fields[] = 'updated_at = NOW()';
$values[] = $id;

$sql = "UPDATE companies SET " . implode(', ', $fields) . " WHERE id = ?";
$db->prepare($sql)->execute($values);

AuditLogger::log('company.updated', 'company', $id, null, ['fields' => array_keys($data)], $decoded);

json_success(null, 'تم تحديث بيانات الشركة بنجاح');
