<?php

require_once __DIR__ . '/agent_schema.php';

if (!function_exists('ua_agent_edit_request_ensure_schema')) {
  function ua_agent_edit_request_ensure_schema(mysqli $conn): void {
    @$conn->query("CREATE TABLE IF NOT EXISTS `agent_subscriber_edit_requests` (
      `id` BIGINT AUTO_INCREMENT PRIMARY KEY,
      `request_token` CHAR(64) NOT NULL,
      `agent_id` INT NOT NULL,
      `subscriber_id` INT NOT NULL,
      `source_instance_id` VARCHAR(80) NULL,
      `request_scope` VARCHAR(24) NOT NULL DEFAULT 'SUBSCRIBER',
      `status` VARCHAR(20) NOT NULL DEFAULT 'PENDING',
      `request_note` VARCHAR(500) NULL,
      `approved_by` INT NULL,
      `approved_at` DATETIME NULL,
      `rejected_by` INT NULL,
      `rejected_at` DATETIME NULL,
      `expires_at` DATETIME NULL,
      `used_at` DATETIME NULL,
      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
      `updated_at` DATETIME NULL,
      UNIQUE KEY `uq_agent_edit_request_token` (`request_token`),
      KEY `idx_agent_edit_request_status` (`status`,`created_at`),
      KEY `idx_agent_edit_request_agent` (`agent_id`,`created_at`),
      KEY `idx_agent_edit_request_scope` (`agent_id`,`request_scope`,`status`,`created_at`),
      KEY `idx_agent_edit_request_subscriber` (`subscriber_id`,`created_at`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $scopeColumn = @$conn->query("SHOW COLUMNS FROM `agent_subscriber_edit_requests` LIKE 'request_scope'");
    if (!$scopeColumn || $scopeColumn->num_rows === 0) {
      @$conn->query("ALTER TABLE `agent_subscriber_edit_requests`
        ADD COLUMN `request_scope` VARCHAR(24) NOT NULL DEFAULT 'SUBSCRIBER' AFTER `source_instance_id`,
        ADD KEY `idx_agent_edit_request_scope` (`agent_id`,`request_scope`,`status`,`created_at`)");
    }
  }
}

if (!function_exists('ua_agent_edit_request_create')) {
  function ua_agent_edit_request_create(mysqli $conn, int $agentId, int $subscriberId, string $note = ''): array {
    ua_agent_edit_request_ensure_schema($conn);
    if ($agentId <= 0 || $subscriberId <= 0) return ['ok'=>false,'error'=>'بيانات الطلب غير صالحة.'];

    $agentStmt = $conn->prepare("SELECT id,linked_instance_id FROM agents WHERE id=? AND is_active=1 AND portal_enabled=1 AND archived_at IS NULL LIMIT 1");
    $agentStmt->bind_param('i', $agentId);
    $agentStmt->execute();
    $agent = $agentStmt->get_result()->fetch_assoc();
    $agentStmt->close();
    if (!$agent) return ['ok'=>false,'error'=>'حساب المعتمد غير صالح.'];

    $subStmt = $conn->prepare("SELECT id FROM subscribers WHERE id=? AND COALESCE(is_deleted,0)=0 LIMIT 1");
    $subStmt->bind_param('i', $subscriberId);
    $subStmt->execute();
    $subscriber = $subStmt->get_result()->fetch_assoc();
    $subStmt->close();
    if (!$subscriber) return ['ok'=>false,'error'=>'المشترك غير موجود.'];

    $pendingStmt = $conn->prepare("SELECT id,request_token FROM agent_subscriber_edit_requests WHERE agent_id=? AND subscriber_id=? AND status='PENDING' ORDER BY id DESC LIMIT 1");
    $pendingStmt->bind_param('ii', $agentId, $subscriberId);
    $pendingStmt->execute();
    $pending = $pendingStmt->get_result()->fetch_assoc();
    $pendingStmt->close();
    if ($pending) return ['ok'=>true,'duplicate'=>true,'id'=>(int)$pending['id'],'token'=>(string)$pending['request_token']];

    $token = bin2hex(random_bytes(32));
    $instanceId = substr(trim((string)($agent['linked_instance_id'] ?? '')), 0, 80);
    $note = mb_substr(trim($note), 0, 500, 'UTF-8');
    $stmt = $conn->prepare("INSERT INTO agent_subscriber_edit_requests
      (request_token,agent_id,subscriber_id,source_instance_id,request_scope,status,request_note,created_at)
      VALUES (?,?,?,?,'SUBSCRIBER','PENDING',?,NOW())");
    $stmt->bind_param('siiss', $token, $agentId, $subscriberId, $instanceId, $note);
    $ok = $stmt->execute();
    $id = $ok ? (int)$stmt->insert_id : 0;
    $error = $ok ? '' : $stmt->error;
    $stmt->close();

    if ($ok && function_exists('ua_agent_activity_add')) {
      ua_agent_activity_add($conn, [
        'agent_id'=>$agentId,
        'event_type'=>'SUBSCRIBER_EDIT_REQUESTED',
        'direction'=>'TO_MAIN',
        'source_instance_id'=>$instanceId,
        'entity_type'=>'subscriber',
        'entity_id'=>(string)$subscriberId,
        'request_id'=>(string)$id,
        'summary'=>'طلب المعتمد صلاحية تعديل بيانات مشترك.',
        'payload'=>['request_id'=>$id,'subscriber_id'=>$subscriberId,'note'=>$note],
        'actor_type'=>'agent',
        'actor_id'=>$agentId,
      ]);
    }
    return ['ok'=>$ok,'duplicate'=>false,'id'=>$id,'token'=>$token,'error'=>$error];
  }
}

if (!function_exists('ua_agent_edit_access_request_create')) {
  function ua_agent_edit_access_request_create(mysqli $conn, int $agentId, string $note = ''): array {
    ua_agent_edit_request_ensure_schema($conn);
    if ($agentId <= 0) return ['ok'=>false,'error'=>'بيانات المعتمد غير صالحة.'];

    $agentStmt = $conn->prepare("SELECT id,linked_instance_id FROM agents WHERE id=? AND is_active=1 AND portal_enabled=1 AND archived_at IS NULL LIMIT 1");
    $agentStmt->bind_param('i', $agentId);
    $agentStmt->execute();
    $agent = $agentStmt->get_result()->fetch_assoc();
    $agentStmt->close();
    if (!$agent) return ['ok'=>false,'error'=>'حساب المعتمد غير صالح.'];

    $activeStmt = $conn->prepare("SELECT id,request_token,status
      FROM agent_subscriber_edit_requests
      WHERE agent_id=? AND request_scope='PORTAL_EDIT'
        AND (status='PENDING' OR (status='APPROVED' AND expires_at>=NOW()))
      ORDER BY CASE WHEN status='APPROVED' THEN 0 ELSE 1 END,id DESC LIMIT 1");
    $activeStmt->bind_param('i', $agentId);
    $activeStmt->execute();
    $active = $activeStmt->get_result()->fetch_assoc();
    $activeStmt->close();
    if ($active) {
      return [
        'ok'=>true,
        'duplicate'=>true,
        'granted'=>(string)$active['status'] === 'APPROVED',
        'id'=>(int)$active['id'],
        'token'=>(string)$active['request_token'],
      ];
    }

    $token = bin2hex(random_bytes(32));
    $instanceId = substr(trim((string)($agent['linked_instance_id'] ?? '')), 0, 80);
    $note = mb_substr(trim($note), 0, 500, 'UTF-8');
    $subscriberId = 0;
    $stmt = $conn->prepare("INSERT INTO agent_subscriber_edit_requests
      (request_token,agent_id,subscriber_id,source_instance_id,request_scope,status,request_note,created_at)
      VALUES (?,?,?,?,'PORTAL_EDIT','PENDING',?,NOW())");
    $stmt->bind_param('siiss', $token, $agentId, $subscriberId, $instanceId, $note);
    $ok = $stmt->execute();
    $id = $ok ? (int)$stmt->insert_id : 0;
    $error = $ok ? '' : $stmt->error;
    $stmt->close();

    if ($ok && function_exists('ua_agent_activity_add')) {
      ua_agent_activity_add($conn, [
        'agent_id'=>$agentId,
        'event_type'=>'SUBSCRIBER_EDIT_ACCESS_REQUESTED',
        'direction'=>'TO_MAIN',
        'source_instance_id'=>$instanceId,
        'entity_type'=>'agent',
        'entity_id'=>(string)$agentId,
        'request_id'=>(string)$id,
        'summary'=>'طلب المعتمد صلاحية مؤقتة للبحث عن المشتركين وتعديل بياناتهم.',
        'payload'=>['request_id'=>$id,'scope'=>'PORTAL_EDIT','note'=>$note],
        'actor_type'=>'agent',
        'actor_id'=>$agentId,
      ]);
    }
    return ['ok'=>$ok,'duplicate'=>false,'granted'=>false,'id'=>$id,'token'=>$token,'error'=>$error];
  }
}

if (!function_exists('ua_agent_edit_request_find')) {
  function ua_agent_edit_request_find(mysqli $conn, string $token, int $agentId = 0, int $subscriberId = 0): ?array {
    ua_agent_edit_request_ensure_schema($conn);
    if (!preg_match('/^[a-f0-9]{64}$/', $token)) return null;
    $sql = "SELECT r.*,a.name agent_name,a.full_name agent_full_name,
      COALESCE(NULLIF(s.full_name,''),TRIM(CONCAT_WS(' ',s.first_name,s.father_name,s.last_name))) subscriber_name
      FROM agent_subscriber_edit_requests r
      JOIN agents a ON a.id=r.agent_id
      LEFT JOIN subscribers s ON s.id=r.subscriber_id
      WHERE r.request_token=?";
    if ($agentId > 0) $sql .= " AND r.agent_id=" . (int)$agentId;
    if ($subscriberId > 0) $sql .= " AND r.subscriber_id=" . (int)$subscriberId;
    $sql .= " LIMIT 1";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $token);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $row ?: null;
  }
}

if (!function_exists('ua_agent_edit_access_request_latest')) {
  function ua_agent_edit_access_request_latest(mysqli $conn, int $agentId): ?array {
    ua_agent_edit_request_ensure_schema($conn);
    if ($agentId <= 0) return null;
    $stmt = $conn->prepare("SELECT request_token
      FROM agent_subscriber_edit_requests
      WHERE agent_id=? AND request_scope='PORTAL_EDIT'
        AND (status='PENDING' OR (status='APPROVED' AND expires_at>=NOW()))
      ORDER BY CASE WHEN status='APPROVED' THEN 0 ELSE 1 END,id DESC LIMIT 1");
    $stmt->bind_param('i', $agentId);
    $stmt->execute();
    $token = (string)($stmt->get_result()->fetch_assoc()['request_token'] ?? '');
    $stmt->close();
    return $token !== '' ? ua_agent_edit_request_find($conn, $token, $agentId, 0) : null;
  }
}

if (!function_exists('ua_agent_edit_request_is_granted')) {
  function ua_agent_edit_request_is_granted(mysqli $conn, string $token, int $agentId, int $subscriberId): bool {
    $row = ua_agent_edit_request_find($conn, $token, $agentId, 0);
    if (!$row || (string)$row['status'] !== 'APPROVED') return false;
    if (empty($row['expires_at']) || strtotime((string)$row['expires_at']) < time()) return false;
    if ((string)($row['request_scope'] ?? 'SUBSCRIBER') === 'PORTAL_EDIT') {
      return (int)($row['subscriber_id'] ?? 0) === 0 && $subscriberId > 0;
    }
    return (int)($row['subscriber_id'] ?? 0) === $subscriberId;
  }
}

if (!function_exists('ua_agent_edit_request_decide')) {
  function ua_agent_edit_request_decide(mysqli $conn, int $requestId, string $decision, int $adminId): array {
    ua_agent_edit_request_ensure_schema($conn);
    $decision = strtoupper($decision);
    if (!in_array($decision, ['APPROVED','REJECTED'], true)) return ['ok'=>false,'error'=>'قرار غير صالح.'];
    $rowRs = @$conn->query("SELECT * FROM agent_subscriber_edit_requests WHERE id=".(int)$requestId." AND status='PENDING' LIMIT 1");
    $row = $rowRs ? $rowRs->fetch_assoc() : null;
    if (!$row) return ['ok'=>false,'error'=>'الطلب غير موجود أو تمت معالجته مسبقاً.'];
    if ($decision === 'APPROVED') {
      $stmt = $conn->prepare("UPDATE agent_subscriber_edit_requests SET status='APPROVED',approved_by=?,approved_at=NOW(),expires_at=DATE_ADD(NOW(),INTERVAL 30 MINUTE),updated_at=NOW() WHERE id=? AND status='PENDING'");
    } else {
      $stmt = $conn->prepare("UPDATE agent_subscriber_edit_requests SET status='REJECTED',rejected_by=?,rejected_at=NOW(),expires_at=NULL,updated_at=NOW() WHERE id=? AND status='PENDING'");
    }
    $stmt->bind_param('ii', $adminId, $requestId);
    $ok = $stmt->execute() && $stmt->affected_rows === 1;
    $error = $ok ? '' : ($stmt->error ?: 'تعذر تحديث الطلب.');
    $stmt->close();
    return ['ok'=>$ok,'error'=>$error,'request'=>$row,'decision'=>$decision];
  }
}
