<?php
/**
 * App API: AC/AAC approve or reject pending application (same as web admin_user_actions).
 * POST: user_id (officer), action=approve|reject, id (applicant user id), role (for approve), rank (for approve).
 */
require_once __DIR__ . '/../config/cors.php';
require_once __DIR__ . '/../config/db.php';

header('Content-Type: application/json');

$response = ['success' => false, 'message' => ''];

try {
    $input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
    $officerUserId = isset($input['user_id']) ? (int) $input['user_id'] : 0;
    $action = trim($input['action'] ?? '');
    $applicantId = isset($input['id']) ? (int) $input['id'] : 0;

    if ($officerUserId <= 0 || !in_array($action, ['approve', 'reject']) || $applicantId <= 0) {
        $response['message'] = 'Missing or invalid user_id, action, or id';
        echo json_encode($response);
        exit;
    }

    $stmt = $pdo->prepare("SELECT id, role, area FROM users WHERE id = ? AND status = 'approved'");
    $stmt->execute([$officerUserId]);
    $officer = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$officer || !in_array($officer['role'], ['AC', 'AAC'])) {
        $response['message'] = 'Unauthorized. AC or AAC only.';
        echo json_encode($response);
        exit;
    }

    $stmt = $pdo->prepare("SELECT first_name, last_name, nroi_id, area, status, role FROM users WHERE id = ?");
    $stmt->execute([$applicantId]);
    $applicant = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$applicant || $applicant['status'] !== 'pending') {
        $response['message'] = 'Applicant not found or not pending';
        echo json_encode($response);
        exit;
    }

    $officerArea = trim($officer['area'] ?? '');
    $applicantArea = trim($applicant['area'] ?? '');
    if ($officerArea === '' || $applicantArea !== $officerArea) {
        $response['message'] = 'You can only approve/reject applications for your area.';
        echo json_encode($response);
        exit;
    }

    $isAc = ($officer['role'] === 'AC');
    $allowedRoles = $isAc ? ['AAC', 'R.O', 'C.R.O'] : ['R.O', 'C.R.O'];
    $role = trim($input['role'] ?? 'R.O');
    if (!in_array($role, $allowedRoles)) {
        $role = 'R.O';
    }
    $rankInput = trim($input['rank'] ?? 'Regular');
    $rank = in_array(strtoupper($rankInput), ['REGULAR', 'OJT', 'INTERN'])
        ? (strtoupper($rankInput) === 'REGULAR' ? 'Regular' : $rankInput)
        : 'Regular';

    $pdo->exec("
        CREATE TABLE IF NOT EXISTS activity_logs (
            id INT AUTO_INCREMENT PRIMARY KEY,
            reference_type VARCHAR(50) NOT NULL,
            reference_id INT NULL,
            description TEXT NOT NULL,
            status VARCHAR(50) NOT NULL,
            performed_by_role VARCHAR(20) NOT NULL,
            performed_by_user_id INT NULL,
            performed_by_admin_id INT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    ");
    $logStmt = $pdo->prepare("
        INSERT INTO activity_logs (reference_type, reference_id, description, status, performed_by_role, performed_by_user_id, performed_by_admin_id)
        VALUES (?, ?, ?, ?, ?, ?, NULL)
    ");

    if ($action === 'approve') {
        $stmt = $pdo->prepare("UPDATE users SET status = 'approved', role = ?, rank = ? WHERE id = ?");
        $stmt->execute([$role, $rank, $applicantId]);
        $desc = "Approved user account: " . ($applicant['first_name'] ?? '') . " " . ($applicant['last_name'] ?? '') . " (NROI ID: " . ($applicant['nroi_id'] ?? 'N/A') . ") - Assigned Rank: {$role}, Area: {$applicantArea}, Status: {$rank}";
        $logStmt->execute(['user', $applicantId, $desc, 'approved', $officer['role'], $officerUserId]);
        $response['success'] = true;
        $response['message'] = 'User approved.';
    } else {
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = ? AND status = 'pending'");
        $stmt->execute([$applicantId]);
        if ($stmt->rowCount() > 0) {
            $desc = "Rejected pending user account: " . ($applicant['first_name'] ?? '') . " " . ($applicant['last_name'] ?? '') . " (NROI ID: " . ($applicant['nroi_id'] ?? 'N/A') . ")";
            $logStmt->execute(['user', $applicantId, $desc, 'rejected', $officer['role'], $officerUserId]);
            $response['success'] = true;
            $response['message'] = 'User rejected and removed.';
        } else {
            $response['message'] = 'Could not reject.';
        }
    }
} catch (Throwable $e) {
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
