<?php
header('Content-Type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', 1);

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

$email = isset($_POST['email']) ? trim($_POST['email']) : '';
if ($email === '') {
    echo json_encode(['success' => false, 'message' => 'Please provide an email']);
    exit;
}

require __DIR__ . '/db_config.php';

// Find user by email
$stmt = $conn->prepare("SELECT id, username, email FROM users WHERE email = ? LIMIT 1");
if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'DB error: prepare failed']);
    exit;
}
$stmt->bind_param('s', $email);
$stmt->execute();
$res = $stmt->get_result();
$user = $res->fetch_assoc();
$stmt->close();

// For security do not reveal account existence in production; for local/dev we may return link
$dev_show = false;
$remote = $_SERVER['REMOTE_ADDR'] ?? '';
if ($remote === '127.0.0.1' || $remote === '::1' || (isset($_GET['debug']) && $_GET['debug'] === '1')) $dev_show = true;

$reset_link = null;
if ($user) {
    // generate token and expiry
    $token = bin2hex(random_bytes(32));
    $expiry = date('Y-m-d H:i:s', time() + 3600); // 1 hour

    // Ensure users table has reset_token/reset_expiry columns. Create them if missing.
    $dbName = isset($DB_NAME) ? $DB_NAME : ( $conn->query("SELECT DATABASE() as db")->fetch_object()->db ?? '' );
    if ($dbName) {
        $colCheck = $conn->prepare("SELECT COUNT(*) as cnt FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'users' AND COLUMN_NAME = ?");
        if ($colCheck) {
            $col = 'reset_token';
            $colCheck->bind_param('ss', $dbName, $col);
            $colCheck->execute();
            $r = $colCheck->get_result()->fetch_assoc();
            if (empty($r) || (int)$r['cnt'] === 0) {
                $conn->query("ALTER TABLE `users` ADD COLUMN `reset_token` VARCHAR(255) NULL DEFAULT NULL");
            }
            $col = 'reset_expiry';
            $colCheck->bind_param('ss', $dbName, $col);
            $colCheck->execute();
            $r2 = $colCheck->get_result()->fetch_assoc();
            if (empty($r2) || (int)$r2['cnt'] === 0) {
                $conn->query("ALTER TABLE `users` ADD COLUMN `reset_expiry` DATETIME NULL DEFAULT NULL");
            }
            $colCheck->close();
        }
    }

    // update user row
    $upd = $conn->prepare("UPDATE users SET reset_token = ?, reset_expiry = ? WHERE id = ?");
    if ($upd) {
        $upd->bind_param('ssi', $token, $expiry, $user['id']);
        $upd->execute();
        $upd->close();
    }

    // Build reset link using same host/dir
    $host = ($_SERVER['HTTP_HOST'] ?? 'localhost');
    $proto = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $reset_link = $proto . '://' . $host . dirname($_SERVER['REQUEST_URI']) . '/reset_password.php?token=' . $token . '&email=' . urlencode($email);

    // Prepare email
    $subject = 'Password Reset Request';
    $body = "Hello " . htmlspecialchars($user['username']) . ",\r\n\r\n";
    $body .= "You requested a password reset. Click the link below to reset your password:\r\n\r\n";
    $body .= $reset_link . "\r\n\r\n";
    $body .= "This link will expire in 1 hour. If you did not request this, ignore this message.\r\n\r\nRegards,\r\nSupport";

    // Load SMTP config from mph_v3 if present
    $cfg = [];
    if (file_exists(__DIR__ . '/mph_v3/mail_config.php')) {
        $cfg = include __DIR__ . '/mph_v3/mail_config.php';
    } elseif (file_exists(__DIR__ . '/mail_config.php')) {
        $cfg = include __DIR__ . '/mail_config.php';
    }

    // Reuse smtp_send helper from mph_v3 (lightweight)
    function smtp_send_local($host, $port, $username, $password, $from, $to, $subject, $body, $encryption = '') {
        $timeout = 10; $errno = 0; $errstr = '';
        $fp = @fsockopen($host, $port, $errno, $errstr, $timeout);
        if (!$fp) return ['ok' => false, 'error' => "Connection failed: $errstr ($errno)"];
        $read = function() use ($fp) { $s = ''; while ($line = fgets($fp, 515)) { $s .= $line; if (substr($line,3,1) == ' ') break; } return $s; };
        $send = function($cmd) use ($fp) { fputs($fp, $cmd . "\r\n"); };
        $read();
        $send("EHLO localhost"); $ehlo = $read();
        if (stripos($ehlo, 'STARTTLS') !== false && strtolower($encryption) === 'tls') {
            $send("STARTTLS"); $read();
            stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
            $send("EHLO localhost"); $read();
        }
        $send('AUTH LOGIN'); $read();
        $send(base64_encode($username)); $read();
        $send(base64_encode($password)); $authRes = $read();
        if (stripos($authRes, '235') === false) { fclose($fp); return ['ok'=>false,'error'=>'SMTP auth failed: '.trim($authRes)]; }
        $send('MAIL FROM: <' . $from . '>'); $read();
        $send('RCPT TO: <' . $to . '>'); $rcpt = $read();
        if (stripos($rcpt,'250')===false && stripos($rcpt,'251')===false) { fclose($fp); return ['ok'=>false,'error'=>'RCPT TO failed: '.trim($rcpt)]; }
        $send('DATA'); $read();
        $headers = "From: " . $from . "\r\n" .
                   "To: " . $to . "\r\n" .
                   "Subject: " . $subject . "\r\n" .
                   "MIME-Version: 1.0\r\n" .
                   "Content-Type: text/plain; charset=UTF-8\r\n\r\n";
        $send($headers . $body . "\r\n.");
        $dataRes = $read();
        $send('QUIT'); $read(); fclose($fp);
        if (stripos($dataRes,'250')===false) return ['ok'=>false,'error'=>'DATA failed: '.trim($dataRes)];
        return ['ok'=>true];
    }

    $sent = false; $sendErr = '';
    // Try PHPMailer if available
    if (file_exists(__DIR__ . '/mph_v3/vendor/autoload.php') || file_exists(__DIR__ . '/vendor/autoload.php')) {
        try {
            if (file_exists(__DIR__ . '/mph_v3/vendor/autoload.php')) require_once __DIR__ . '/mph_v3/vendor/autoload.php';
            else require_once __DIR__ . '/vendor/autoload.php';
            $mail = new PHPMailer\PHPMailer\PHPMailer(true);
            $mail->isSMTP();
            $mail->Host = $cfg['host'] ?? '';
            $mail->SMTPAuth = true;
            $mail->Username = $cfg['username'] ?? '';
            $mail->Password = $cfg['password'] ?? '';
            if (!empty($cfg['encryption'])) $mail->SMTPSecure = $cfg['encryption'];
            $mail->Port = $cfg['port'] ?? 587;
            $mail->setFrom($cfg['from_email'] ?? 'noreply@local', $cfg['from_name'] ?? 'Support');
            $mail->addAddress($email, $user['username']);
            $mail->Subject = $subject;
            $mail->Body = $body;
            $mail->AltBody = strip_tags($body);
            $mail->send();
            $sent = true;
        } catch (Exception $e) {
            $sendErr = 'PHPMailer: ' . $e->getMessage();
        }
    }

    if (!$sent) {
        if (!empty($cfg) && !empty($cfg['host']) && !empty($cfg['username'])) {
            $smtpRes = smtp_send_local($cfg['host'], $cfg['port'] ?? 587, $cfg['username'], $cfg['password'] ?? '', $cfg['from_email'] ?? $cfg['username'], $email, $subject, $body, $cfg['encryption'] ?? '');
            if ($smtpRes['ok']) $sent = true; else $sendErr = $smtpRes['error'] ?? 'Unknown SMTP error';
        } else {
            $sendErr = 'SMTP not configured (see mph_v3/mail_config.php)';
        }
    }

    if ($sent) {
        // Inform the user that the reset email was sent successfully
        $out = ['success' => true, 'message' => 'Password reset email has been sent successfully.'];
        if ($dev_show) $out['reset_link'] = $reset_link;
        echo json_encode($out);
        $conn->close();
        exit;
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to send email: ' . $sendErr]);
        $conn->close();
        exit;
    }
}

// If user not found, return an explicit message (user requested behaviour)
echo json_encode(['success' => false, 'message' => 'No account is registered with this email. Please sign up.']);
$conn->close();
