<?php

require_once __DIR__ . '/agent_schema.php';

if (!function_exists('ua_agent_repo_get')) {
  function ua_agent_repo_get(mysqli $conn, int $agentId, bool $includeArchived = false): ?array {
    ua_agent_schema_migrate($conn);
    if ($agentId <= 0) return null;
    $where = $includeArchived ? '' : ' AND archived_at IS NULL';
    $stmt = $conn->prepare("SELECT * FROM agents WHERE id=?{$where} LIMIT 1");
    if (!$stmt) return null;
    $stmt->bind_param('i', $agentId);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = ($res && $res->num_rows) ? $res->fetch_assoc() : null;
    $stmt->close();
    return $row ?: null;
  }
}

if (!function_exists('ua_agent_repo_list')) {
  function ua_agent_repo_list(mysqli $conn, array $filters = []): array {
    ua_agent_schema_migrate($conn);
    $where = ['1=1'];
    if (empty($filters['include_archived'])) $where[] = 'a.archived_at IS NULL';
    if (isset($filters['active']) && $filters['active'] !== '') $where[] = 'a.is_active=' . ((int)$filters['active'] ? '1' : '0');
    if (!empty($filters['q'])) {
      $q = $conn->real_escape_string(trim((string)$filters['q']));
      $where[] = "(a.name LIKE '%{$q}%' OR a.full_name LIKE '%{$q}%' OR a.code LIKE '%{$q}%' OR a.username LIKE '%{$q}%' OR a.phone LIKE '%{$q}%')";
    }
    $rows = [];
    $rs = @$conn->query("SELECT a.* FROM agents a WHERE " . implode(' AND ', $where) . " ORDER BY a.is_active DESC, a.full_name ASC, a.id DESC");
    if ($rs) while ($row = $rs->fetch_assoc()) $rows[] = $row;
    return $rows;
  }
}

if (!function_exists('ua_agent_repo_save')) {
  function ua_agent_repo_save(mysqli $conn, array $data, int $actorId = 0): array {
    ua_agent_schema_migrate($conn);
    $id = (int)($data['id'] ?? 0);
    $name = trim((string)($data['full_name'] ?? $data['name'] ?? ''));
    $code = strtoupper(trim((string)($data['code'] ?? '')));
    $username = strtolower(trim((string)($data['username'] ?? '')));
    if ($name === '') return ['ok'=>false,'error'=>'اسم المعتمد مطلوب.','id'=>$id];
    if ($code === '') $code = 'AG-' . strtoupper(substr(sha1($name . microtime(true)), 0, 8));
    if ($username === '') return ['ok'=>false,'error'=>'اسم المستخدم مطلوب.','id'=>$id];

    $commissionType = (string)($data['commission_type'] ?? 'none');
    if (!in_array($commissionType, ['none','fixed','percent'], true)) $commissionType = 'none';
    $fields = [
      'code'=>$code, 'name'=>$name, 'full_name'=>$name,
      'national_id'=>trim((string)($data['national_id'] ?? '')),
      'phone'=>trim((string)($data['phone'] ?? '')),
      'phone_alt'=>trim((string)($data['phone_alt'] ?? '')),
      'email'=>trim((string)($data['email'] ?? '')),
      'address'=>trim((string)($data['address'] ?? '')),
      'area'=>trim((string)($data['area'] ?? '')),
      'notes'=>trim((string)($data['notes'] ?? '')),
      'username'=>$username,
      'is_active'=>!empty($data['is_active']) ? 1 : 0,
      'portal_enabled'=>!empty($data['portal_enabled']) ? 1 : 0,
      'pos_enabled'=>!empty($data['pos_enabled']) ? 1 : 0,
      'linked_instance_id'=>trim((string)($data['linked_instance_id'] ?? '')),
      'commission_type'=>$commissionType,
      'commission_value'=>(float)($data['commission_value'] ?? 0),
      'credit_limit'=>($data['credit_limit'] ?? '') === '' ? null : (float)$data['credit_limit'],
    ];
    $password = (string)($data['password'] ?? '');
    $pin = (string)($data['pin'] ?? '');

    try {
      if ($id > 0) {
        $stmt = $conn->prepare("UPDATE agents SET code=?,name=?,full_name=?,national_id=?,phone=?,phone_alt=?,email=?,address=?,area=?,notes=?,username=?,is_active=?,portal_enabled=?,pos_enabled=?,linked_instance_id=?,commission_type=?,commission_value=?,credit_limit=?,updated_by=?,updated_at=NOW() WHERE id=? AND archived_at IS NULL");
        if (!$stmt) throw new RuntimeException($conn->error);
        $stmt->bind_param(
          'sssssssssssiiissddii',
          $fields['code'],$fields['name'],$fields['full_name'],$fields['national_id'],$fields['phone'],$fields['phone_alt'],
          $fields['email'],$fields['address'],$fields['area'],$fields['notes'],$fields['username'],$fields['is_active'],
          $fields['portal_enabled'],$fields['pos_enabled'],$fields['linked_instance_id'],$fields['commission_type'],
          $fields['commission_value'],$fields['credit_limit'],$actorId,$id
        );
      } else {
        $stmt = $conn->prepare("INSERT INTO agents (code,name,full_name,national_id,phone,phone_alt,email,address,area,notes,username,is_active,portal_enabled,pos_enabled,linked_instance_id,commission_type,commission_value,credit_limit,created_by,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW())");
        if (!$stmt) throw new RuntimeException($conn->error);
        $stmt->bind_param(
          'sssssssssssiiissddi',
          $fields['code'],$fields['name'],$fields['full_name'],$fields['national_id'],$fields['phone'],$fields['phone_alt'],
          $fields['email'],$fields['address'],$fields['area'],$fields['notes'],$fields['username'],$fields['is_active'],
          $fields['portal_enabled'],$fields['pos_enabled'],$fields['linked_instance_id'],$fields['commission_type'],
          $fields['commission_value'],$fields['credit_limit'],$actorId
        );
      }
      if (!$stmt->execute()) throw new RuntimeException($stmt->error);
      if ($id <= 0) $id = (int)$stmt->insert_id;
      $stmt->close();

      $sets = [];
      if ($password !== '') $sets[] = "password_hash='" . $conn->real_escape_string(password_hash($password, PASSWORD_DEFAULT)) . "'";
      if ($pin !== '') $sets[] = "pin_hash='" . $conn->real_escape_string(password_hash($pin, PASSWORD_DEFAULT)) . "'";
      if ($sets) @$conn->query("UPDATE agents SET " . implode(',', $sets) . " WHERE id={$id}");
      return ['ok'=>true,'error'=>'','id'=>$id];
    } catch (Throwable $e) {
      return ['ok'=>false,'error'=>$e->getMessage(),'id'=>$id];
    }
  }
}

if (!function_exists('ua_agent_repo_archive')) {
  function ua_agent_repo_archive(mysqli $conn, int $agentId, int $actorId = 0): bool {
    ua_agent_schema_migrate($conn);
    if ($agentId <= 0) return false;
    $stmt = $conn->prepare("UPDATE agents SET is_active=0,portal_enabled=0,pos_enabled=0,archived_at=NOW(),updated_by=?,updated_at=NOW() WHERE id=? AND archived_at IS NULL");
    if (!$stmt) return false;
    $stmt->bind_param('ii', $actorId, $agentId);
    $ok = $stmt->execute();
    $stmt->close();
    return (bool)$ok;
  }
}

if (!function_exists('ua_agent_repo_change_password')) {
  function ua_agent_repo_change_password(mysqli $conn, int $agentId, string $currentPassword, string $newPassword): array {
    $agent = ua_agent_repo_get($conn, $agentId);
    if (!$agent) return ['ok'=>false,'error'=>'حساب المعتمد غير موجود.'];
    if (!function_exists('ua_agent_password_ok')) {
      require_once __DIR__ . '/agent_lib.php';
    }
    if (!ua_agent_password_ok($agent, $currentPassword, false)) {
      return ['ok'=>false,'error'=>'كلمة المرور الحالية غير صحيحة.'];
    }
    if (strlen($newPassword) < 8) {
      return ['ok'=>false,'error'=>'يجب ألا تقل كلمة المرور الجديدة عن 8 محارف.'];
    }

    $hash = password_hash($newPassword, PASSWORD_DEFAULT);
    $stmt = $conn->prepare("UPDATE agents SET password_hash=?,updated_at=NOW() WHERE id=? AND archived_at IS NULL");
    if (!$stmt) return ['ok'=>false,'error'=>'تعذر تجهيز تحديث كلمة المرور.'];
    $stmt->bind_param('si', $hash, $agentId);
    $ok = $stmt->execute() && $stmt->affected_rows === 1;
    $error = $ok ? '' : ($stmt->error ?: 'تعذر تحديث كلمة المرور.');
    $stmt->close();
    return ['ok'=>$ok,'error'=>$error];
  }
}
