<?php
// ============================================================
//  db/reset-password.php
// ============================================================
//
//  Reset a member's password from the command line.
//  Useful when the email-based reset flow isn't working (e.g.
//  mail() is broken, or the member's email is wrong on file).
//
//  Usage:
//
//    # Reset to a specific password:
//    php db/reset-password.php --email=admin@elegantwork.co.za --password='new-one'
//
//    # Generate a random password (script prints it):
//    php db/reset-password.php --email=admin@elegantwork.co.za --generate
//
//    # List accounts by partial email match (no changes):
//    php db/reset-password.php --find=elegant
//
//  Refuses to run except from CLI.
//
// ============================================================

if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    exit("This script must be run from the command line.\n");
}

require_once __DIR__ . '/../includes/db.php';

// ---- Parse --key=value args ----
$args = [];
foreach (array_slice($argv, 1) as $arg) {
    if (preg_match('/^--([^=]+)(?:=(.*))?$/', $arg, $m)) {
        $args[$m[1]] = $m[2] ?? true;   // flags without values become `true`
    }
}

// ---- Mode 1: find users ----
if (!empty($args['find'])) {
    $needle = '%' . $args['find'] . '%';
    $rows = db_all(
        'SELECT id, email, first_name, last_name, business_name, role, status
           FROM members WHERE email LIKE :n OR business_name LIKE :n
           ORDER BY id',
        ['n' => $needle]
    );
    if (!$rows) {
        echo "No members match '{$args['find']}'.\n";
        exit(0);
    }
    echo "Matches:\n";
    foreach ($rows as $r) {
        printf(
            "  #%-4d  %-40s  %-25s  %s / %s\n",
            $r['id'], $r['email'], $r['business_name'], $r['role'], $r['status']
        );
    }
    exit(0);
}

// ---- Mode 2: reset ----
$email = strtolower(trim($args['email'] ?? ''));

if (!$email) {
    fwrite(STDERR, "Usage:\n");
    fwrite(STDERR, "  php db/reset-password.php --email=USER --password=NEW_PW\n");
    fwrite(STDERR, "  php db/reset-password.php --email=USER --generate\n");
    fwrite(STDERR, "  php db/reset-password.php --find=SEARCH\n");
    exit(1);
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    fwrite(STDERR, "Error: '$email' is not a valid email\n");
    exit(1);
}

$member = db_row(
    'SELECT id, email, first_name, last_name, business_name, role, status
       FROM members WHERE email = :e',
    ['e' => $email]
);
if (!$member) {
    fwrite(STDERR, "Error: no member found with email $email\n");
    fwrite(STDERR, "Use --find=partial to search by partial email.\n");
    exit(1);
}

// Decide the new password
$new_password = $args['password'] ?? '';
$was_generated = false;

if (!empty($args['generate'])) {
    // 18 chars of hex = 72 bits of entropy. Enough for an admin account.
    $new_password = bin2hex(random_bytes(9));
    $was_generated = true;
}

if (!$new_password) {
    fwrite(STDERR, "Error: provide either --password=NEW or --generate\n");
    exit(1);
}

if (strlen($new_password) < 8) {
    fwrite(STDERR, "Error: password must be at least 8 characters\n");
    exit(1);
}

// ---- Confirm destination before wiping ----
echo "About to reset password for:\n";
printf(
    "  #%d  %s  (%s %s, %s, role=%s)\n",
    $member['id'], $member['email'],
    $member['first_name'], $member['last_name'],
    $member['business_name'], $member['role']
);

// Prompt for confirmation (skippable with --yes for scripted use)
if (empty($args['yes'])) {
    echo "Continue? [y/N] ";
    $reply = strtolower(trim((string)fgets(STDIN)));
    if ($reply !== 'y' && $reply !== 'yes') {
        echo "Aborted. No changes made.\n";
        exit(0);
    }
}

// ---- Apply ----
$hash = password_hash($new_password, PASSWORD_BCRYPT, ['cost' => AUTH_BCRYPT_COST]);
db_exec(
    'UPDATE members SET password_hash = :h WHERE id = :id',
    ['h' => $hash, 'id' => $member['id']]
);

// Invalidate any outstanding reset tokens for this member
db_exec(
    'UPDATE password_resets SET used_at = NOW()
       WHERE member_id = :id AND used_at IS NULL',
    ['id' => $member['id']]
);

echo "\nPassword updated for {$member['email']}.\n";

if ($was_generated) {
    echo "\n  NEW PASSWORD:  {$new_password}\n\n";
    echo "Copy it now — it is not stored anywhere in plaintext.\n";
}

echo "\nThey can sign in at " . (defined('SITE_URL') ? SITE_URL : '') . "/login.php\n";
