<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/auth_admin.php';
require_once __DIR__ . '/../../includes/audit.php';

apply_cors();
$admin = require_admin();
$pdo = getDbConnection();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

// ============================================================
// GET /users.php            -> list (search, filter, paginate)
// GET /users.php?id=5       -> single user detail (+ recent calls & payments)
// POST /users.php           -> create user (admin-created, credentials generated)
// PUT /users.php?id=5       -> update profile fields
// PATCH /users.php?id=5&action=status   -> block/unblock
// PATCH /users.php?id=5&action=plan     -> change plan / extend validity
// POST /users.php?action=reset-password -> { id }
// POST /users.php?action=reset-device   -> { id }
// DELETE /users.php?id=5    -> delete user
// ============================================================

if ($method === 'GET' && isset($_GET['id'])) {
    $id = (int) $_GET['id'];
    $stmt = $pdo->prepare(
        "SELECT id, full_name, email, phone_number, business_name, gst_number, address,
                website_url, role, license_key, validity_days, activated_at, is_blocked,
                is_email_verified, active_device_id, last_login, created_at
         FROM users WHERE id = :id LIMIT 1"
    );
    $stmt->execute([':id' => $id]);
    $user = $stmt->fetch();
    if (!$user) {
        send_error('User not found.', 404);
    }

    $calls = $pdo->prepare(
        'SELECT id, phone_number, call_type, status, channel_used, created_at
         FROM call_logs WHERE user_email = :email ORDER BY created_at DESC LIMIT 10'
    );
    $calls->execute([':email' => $user['email']]);

    $payments = $pdo->prepare(
        'SELECT id, plan_name, amount, gateway, status, created_at
         FROM payment_transactions WHERE user_email = :email ORDER BY created_at DESC LIMIT 10'
    );
    $payments->execute([':email' => $user['email']]);

    send_success([
        'user'     => $user,
        'recent_calls'    => $calls->fetchAll(),
        'recent_payments' => $payments->fetchAll(),
    ]);
}

if ($method === 'GET') {
    [$page, $perPage, $offset] = paginate_params();
    $search = clean_str($_GET['search'] ?? '');
    $status = clean_str($_GET['status'] ?? ''); // active|expired|blocked|trial|paid

    $where = ["role = 'USER'"];
    $params = [];

    if ($search !== '') {
        $where[] = '(full_name LIKE :search OR email LIKE :search2 OR phone_number LIKE :search3)';
        $params[':search']  = "%$search%";
        $params[':search2'] = "%$search%";
        $params[':search3'] = "%$search%";
    }

    switch ($status) {
        case 'blocked':
            $where[] = 'is_blocked = 1';
            break;
        case 'active':
            $where[] = 'is_blocked = 0 AND DATE_ADD(activated_at, INTERVAL validity_days DAY) >= NOW()';
            break;
        case 'expired':
            $where[] = 'is_blocked = 0 AND DATE_ADD(activated_at, INTERVAL validity_days DAY) < NOW()';
            break;
        case 'trial':
            $where[] = 'validity_days <= 2';
            break;
        case 'paid':
            $where[] = 'validity_days > 2';
            break;
    }

    $whereSql = implode(' AND ', $where);

    $countStmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE $whereSql");
    $countStmt->execute($params);
    $total = (int) $countStmt->fetchColumn();

    $listStmt = $pdo->prepare(
        "SELECT id, full_name, email, phone_number, business_name, role, license_key,
                validity_days, activated_at, is_blocked, active_device_id, last_login, created_at
         FROM users WHERE $whereSql ORDER BY created_at DESC LIMIT :limit OFFSET :offset"
    );
    foreach ($params as $key => $val) {
        $listStmt->bindValue($key, $val);
    }
    $listStmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
    $listStmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $listStmt->execute();

    send_success([
        'users' => $listStmt->fetchAll(),
        'pagination' => ['page' => $page, 'per_page' => $perPage, 'total' => $total, 'total_pages' => (int) ceil($total / $perPage)],
    ]);
}

if ($method === 'POST' && $action === 'reset-password') {
    $input = get_json_input();
    require_fields($input, ['id']);
    $newPassword = generate_token(6);
    $hash = password_hash($newPassword, PASSWORD_DEFAULT);

    $stmt = $pdo->prepare('UPDATE users SET password_hash = :hash WHERE id = :id AND role = "USER"');
    $stmt->execute([':hash' => $hash, ':id' => (int) $input['id']]);

    if ($stmt->rowCount() === 0) {
        send_error('User not found.', 404);
    }

    log_admin_action($admin['email'], 'RESET_USER_PASSWORD', 'user_id:' . $input['id'], '');
    send_success(['new_password' => $newPassword], 'Password reset. Share this new password securely with the user.');
}

if ($method === 'POST' && $action === 'reset-device') {
    $input = get_json_input();
    require_fields($input, ['id']);

    $stmt = $pdo->prepare('UPDATE users SET active_device_id = NULL WHERE id = :id AND role = "USER"');
    $stmt->execute([':id' => (int) $input['id']]);

    if ($stmt->rowCount() === 0) {
        send_error('User not found.', 404);
    }

    log_admin_action($admin['email'], 'RESET_DEVICE_LOCK', 'user_id:' . $input['id'], '');
    send_success(null, 'Device lock reset. User can now log in on a new device.');
}

if ($method === 'POST') {
    $input = get_json_input();
    require_fields($input, ['full_name', 'email', 'plan_id']);

    $email = strtolower(clean_str($input['email']));
    if (!is_valid_email($email)) {
        send_error('Invalid email address.', 422);
    }

    $existing = $pdo->prepare('SELECT id FROM users WHERE email = :email');
    $existing->execute([':email' => $email]);
    if ($existing->fetch()) {
        send_error('A user with this email already exists.', 409);
    }

    $plan = $pdo->prepare('SELECT * FROM subscriptions WHERE id = :id AND is_active = 1');
    $plan->execute([':id' => (int) $input['plan_id']]);
    $planRow = $plan->fetch();
    if (!$planRow) {
        send_error('Selected plan not found.', 404);
    }

    $tempPassword = generate_token(6);
    $hash = password_hash($tempPassword, PASSWORD_DEFAULT);
    $licenseKey = strtoupper('LIC-' . bin2hex(random_bytes(4)));

    $stmt = $pdo->prepare(
        'INSERT INTO users (full_name, email, password_hash, phone_number, business_name, role,
                             license_key, validity_days, is_blocked, is_email_verified)
         VALUES (:full_name, :email, :hash, :phone, :business, "USER", :license, :validity, 0, 1)'
    );
    $stmt->execute([
        ':full_name' => clean_str($input['full_name']),
        ':email'     => $email,
        ':hash'      => $hash,
        ':phone'     => clean_str($input['phone_number'] ?? ''),
        ':business'  => clean_str($input['business_name'] ?? ''),
        ':license'   => $licenseKey,
        ':validity'  => (int) $planRow['validity_days'],
    ]);

    $newId = (int) $pdo->lastInsertId();
    log_admin_action($admin['email'], 'CREATE_USER', 'user_id:' . $newId, 'Created user ' . $email);

    send_success([
        'user_id'       => $newId,
        'email'         => $email,
        'temp_password' => $tempPassword,
        'license_key'   => $licenseKey,
    ], 'User created. Share the credentials with the user (e.g. via WhatsApp).', 201);
}

if ($method === 'PUT' && isset($_GET['id'])) {
    $id = (int) $_GET['id'];
    $input = get_json_input();

    $fields = [];
    $params = [':id' => $id];
    foreach (['full_name', 'phone_number', 'business_name', 'gst_number', 'address', 'website_url'] as $f) {
        if (isset($input[$f])) {
            $fields[] = "$f = :$f";
            $params[":$f"] = clean_str($input[$f]);
        }
    }
    if (empty($fields)) {
        send_error('No fields to update.', 422);
    }

    $stmt = $pdo->prepare('UPDATE users SET ' . implode(', ', $fields) . ' WHERE id = :id AND role = "USER"');
    $stmt->execute($params);

    log_admin_action($admin['email'], 'UPDATE_USER', 'user_id:' . $id, json_encode($input));
    send_success(null, 'User updated.');
}

if ($method === 'PATCH' && isset($_GET['id']) && $action === 'status') {
    $id = (int) $_GET['id'];
    $input = get_json_input();
    require_fields($input, ['is_blocked']);

    $stmt = $pdo->prepare('UPDATE users SET is_blocked = :blocked WHERE id = :id AND role = "USER"');
    $stmt->execute([':blocked' => $input['is_blocked'] ? 1 : 0, ':id' => $id]);

    log_admin_action($admin['email'], $input['is_blocked'] ? 'BLOCK_USER' : 'UNBLOCK_USER', 'user_id:' . $id, '');
    send_success(null, $input['is_blocked'] ? 'User blocked.' : 'User unblocked.');
}

if ($method === 'PATCH' && isset($_GET['id']) && $action === 'plan') {
    $id = (int) $_GET['id'];
    $input = get_json_input();
    require_fields($input, ['validity_days']);

    $stmt = $pdo->prepare(
        'UPDATE users SET validity_days = :validity, activated_at = NOW() WHERE id = :id AND role = "USER"'
    );
    $stmt->execute([':validity' => (int) $input['validity_days'], ':id' => $id]);

    if (isset($input['license_key'])) {
        $lk = $pdo->prepare('UPDATE users SET license_key = :lk WHERE id = :id');
        $lk->execute([':lk' => clean_str($input['license_key']), ':id' => $id]);
    }

    log_admin_action($admin['email'], 'CHANGE_USER_PLAN', 'user_id:' . $id, 'validity_days=' . $input['validity_days']);
    send_success(null, 'Plan / validity updated. Timer restarts from now.');
}

if ($method === 'DELETE' && isset($_GET['id'])) {
    $id = (int) $_GET['id'];
    $stmt = $pdo->prepare('DELETE FROM users WHERE id = :id AND role = "USER"');
    $stmt->execute([':id' => $id]);

    if ($stmt->rowCount() === 0) {
        send_error('User not found.', 404);
    }

    log_admin_action($admin['email'], 'DELETE_USER', 'user_id:' . $id, '');
    send_success(null, 'User deleted.');
}

send_error('Invalid request.', 400);
