<?php
session_start();
require_once '../connect.php';
require_once './mailer/vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

header('Content-Type: application/json');
$raw = file_get_contents('php://input');
$json = $raw ? json_decode($raw, true) : [];
$action = $_POST['action'] ?? ($json['action'] ?? 'request');

function public_url_base() {
    $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
    $scheme = $https ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $dir = rtrim(dirname(dirname($_SERVER['SCRIPT_NAME'] ?? '/')), '/\\');
    return $scheme . '://' . $host . ($dir === '/' ? '' : $dir);
}
function sendResetEmail($to, $name, $link) {
    global $conn;
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host       = 'smtp.gmail.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'monzermahfouz54321m@gmail.com';
        $mail->Password   = 'qxsx gwuz eies yiqi';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;
        $fromEmail = 'monzermahfouz54321m@gmail.com';
        $mail->setFrom($fromEmail, 'Shark CRM');
        $mail->addAddress($to, $name);
        $mail->isHTML(true);
        $mail->Subject = 'Reset your Shark CRM password';
        $mail->Body = '<div style="font-family:Arial,sans-serif;line-height:1.6"><h2>Password Reset</h2><p>Hello '.htmlspecialchars($name).',</p><p>Click the button below to reset your password. This link expires in 1 hour.</p><p><a style="background:#1a3a6f;color:#fff;padding:12px 18px;border-radius:8px;text-decoration:none" href="'.htmlspecialchars($link).'">Reset Password</a></p><p>If you did not request this, ignore this email.</p></div>';
        $mail->AltBody = "Reset your password: $link";
        $mail->send();
        return true;
    } catch (Exception $e) {
        return false;
    }
}

if ($action === 'request') {
    $email = sanitize($conn, $_POST['email'] ?? ($json['email'] ?? ''));
    if (!$email) jsonResponse(false, 'Email required');
    $q = $conn->query("SELECT id, name, email FROM users WHERE email='$email' LIMIT 1");
    // Never reveal whether email exists.
    if ($q && $q->num_rows) {
        $u = $q->fetch_assoc();
        $token = bin2hex(random_bytes(32));
        $hash = password_hash($token, PASSWORD_DEFAULT);
        $hash = $conn->real_escape_string($hash);
        $expires = date('Y-m-d H:i:s', time() + 3600);
        $uid = (int)$u['id'];
        $conn->query("UPDATE users SET reset_token='$hash', reset_expires='$expires' WHERE id=$uid");
        $link = public_url_base() . '/index.php?page=login&reset_token=' . urlencode($token) . '&email=' . urlencode($u['email']);
        sendResetEmail($u['email'], $u['name'], $link);
    }
    jsonResponse(true, 'If this email exists, a reset link was sent.');
}

if ($action === 'reset') {
    $email = sanitize($conn, $_POST['email'] ?? ($json['email'] ?? ''));
    $token = $_POST['token'] ?? ($json['token'] ?? '');
    $password = $_POST['password'] ?? ($json['password'] ?? '');
    if (!$email || !$token || strlen($password) < 6) jsonResponse(false, 'Invalid reset request');
    $q = $conn->query("SELECT id, reset_token, reset_expires FROM users WHERE email='$email' LIMIT 1");
    if (!$q || !$q->num_rows) jsonResponse(false, 'Invalid or expired link');
    $u = $q->fetch_assoc();
    if (!$u['reset_token'] || strtotime($u['reset_expires']) < time() || !password_verify($token, $u['reset_token'])) {
        jsonResponse(false, 'Invalid or expired link');
    }
    $hash = $conn->real_escape_string(password_hash($password, PASSWORD_DEFAULT));
    $uid = (int)$u['id'];
    $conn->query("UPDATE users SET password='$hash', reset_token=NULL, reset_expires=NULL WHERE id=$uid");
    jsonResponse(true, 'Password updated. You can login now.');
}
jsonResponse(false, 'Invalid action');
