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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['email'])) {
    $email = trim($_POST['email']);

    require_once __DIR__ . '/db_config.php';
    
    $conn = $conn;  // Already set by db_config.php
    if ($conn->connect_error) {
        $response['message'] = 'Database connection error';
        echo json_encode($response);
        exit();
    }
    $conn->set_charset('utf8mb4');

    // Check if email exists
    $stmt = $conn->prepare("SELECT `sno`, `name` FROM `login-t` WHERE `email` = ?");
    if (!$stmt) {
        $response['message'] = 'Database error';
        echo json_encode($response);
        exit();
    }
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    // Allow showing token in response for local/dev testing (not for production)
    $dev_show_token = false;
    $remoteAddr = $_SERVER['REMOTE_ADDR'] ?? '';
    if ($remoteAddr === '127.0.0.1' || $remoteAddr === '::1' || (isset($_GET['debug']) && $_GET['debug'] === '1')) {
        $dev_show_token = true;
    }

    if ($result->num_rows > 0) {
        // Email exists - generate reset token
        $row = $result->fetch_assoc();
        $userId = $row['sno'];
        $userName = $row['name'];

        $resetToken = bin2hex(random_bytes(32));
        $expiryTime = date('Y-m-d H:i:s', strtotime('+45 minutes'));
        
        $updateStmt = $conn->prepare("UPDATE `login-t` SET `reset_token` = ?, `reset_expiry` = ? WHERE `sno` = ?");
        if (!$updateStmt) {
            $response['message'] = 'Database error';
            echo json_encode($response);
            exit();
        }
        $updateStmt->bind_param("ssi", $resetToken, $expiryTime, $userId);
        $updateStmt->execute();
        $updateStmt->close();

        // Send email using SMTP helper and config
        $resetLink = "http://localhost/MPH_V3/verify_reset.php?token=" . $resetToken . "&email=" . urlencode($email);
        $subject = "Password Reset Request";
        $body = "Hello " . htmlspecialchars($userName) . ",\r\n\r\n";
        $body .= "You requested to reset your password. Click the link below to proceed:\r\n\r\n";
        $body .= $resetLink . "\r\n\r\n";
        $body .= "This link will expire in 1 hour.\r\n\r\n";
        $body .= "If you did not request this, please ignore this email.\r\n\r\n";
        $body .= "Regards,\r\nYour Website Team";

        // load config
        $cfg = [];
        if (file_exists(__DIR__ . '/mail_config.php')) {
            $cfg = include __DIR__ . '/mail_config.php';
        }

        // simple SMTP send helper (works with Mailtrap or other basic SMTP servers)
        function smtp_send($host, $port, $username, $password, $from, $to, $subject, $body, $encryption = '') {
            $timeout = 10;
            $errno = 0; $errstr = '';
            $remote = $host . ':' . $port;
            $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"); };

            $greeting = $read();
            // EHLO
            $send("EHLO localhost"); $ehlo = $read();
            // If server supports STARTTLS and encryption requested
            if (stripos($ehlo, 'STARTTLS') !== false && strtolower($encryption) === 'tls') {
                $send("STARTTLS"); $read();
                stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
                // EHLO again after STARTTLS
                $send("EHLO localhost"); $read();
            }

            // AUTH LOGIN
            $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)];
            }

            // MAIL FROM
            $send('MAIL FROM: <' . $from . '>'); $read();
            // RCPT TO
            $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)];
            }

            // DATA
            $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();
            // QUIT
            $send('QUIT'); $read();
            fclose($fp);
            if (stripos($dataRes, '250') === false) return ['ok' => false, 'error' => 'DATA failed: ' . trim($dataRes)];
            return ['ok' => true];
        }

        // Try PHPMailer (recommended) if available via Composer, otherwise fallback to our smtp_send helper
        $sent = false;
        $sendError = '';

        // If PHPMailer is installed via Composer, use it (more robust)
        if (file_exists(__DIR__ . '/vendor/autoload.php')) {
            try {
                require_once __DIR__ . '/vendor/autoload.php';
                $mail = new PHPMailer\PHPMailer\PHPMailer(true);
                // SMTP config from $cfg
                $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.test', $cfg['from_name'] ?? 'Website');
                $mail->addAddress($email, $userName);
                $mail->Subject = $subject;
                $mail->Body = $body;
                $mail->AltBody = strip_tags($body);
                $mail->send();
                $sent = true;
            } catch (Exception $e) {
                $sendError = 'PHPMailer error: ' . $e->getMessage();
            }
        }

        if (!$sent) {
            // fallback to custom smtp helper if config available
            if (!empty($cfg) && !empty($cfg['host']) && !empty($cfg['username'])) {
                $smtpRes = smtp_send($cfg['host'], $cfg['port'], $cfg['username'], $cfg['password'], $cfg['from_email'], $email, $subject, $body, $cfg['encryption'] ?? '');
                        if ($smtpRes['ok']) {
                            $response['success'] = true;
                            $response['message'] = 'Password reset link has been sent to your email.';
                            if ($dev_show_token) $response['debug_token'] = $resetToken;
                        } else {
                            $response['message'] = 'Email sending failed. ' . ($smtpRes['error'] ?? '') . ($sendError ? ' | ' . $sendError : '');
                        }
            } else {
                // no SMTP config — advise user
                        $response['message'] = 'Email sending not configured. Please set SMTP credentials in mail_config.php';
                        if ($sendError) $response['message'] .= ' | ' . $sendError;
                        if ($dev_show_token) $response['debug_token'] = $resetToken;
            }
        } else {
                    $response['success'] = true;
                    $response['message'] = 'Password reset link has been sent to your email.';
                    if ($dev_show_token) $response['debug_token'] = $resetToken;
        }
    } else {
        // Email not found
        $response['message'] = 'no_account';
    }

    $stmt->close();
    $conn->close();
}

echo json_encode($response);
?>
