<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;
use App\Core\ConferenceMailer;

class ForgotPasswordController extends Controller
{
    public function index()
    {
        require BASE_PATH.'/app/views/auth/forgot_password.php';
    }

    public function send()
    {
        $email=trim($_POST['email'] ?? '');

        if(!$email){
            exit('Email required');
        }

        $db=Database::getInstance();

        $stmt=$db->prepare("
            SELECT *
            FROM users
            WHERE email=?
            LIMIT 1
        ");

        $stmt->execute([$email]);

        $user=$stmt->fetch(\PDO::FETCH_ASSOC);

        if(!$user){
            exit('User not found');
        }

        $token=bin2hex(random_bytes(32));

        $db->prepare("
            INSERT INTO password_reset_tokens
            (user_id,email,token,expires_at)
            VALUES
            (?,?,?,DATE_ADD(NOW(),INTERVAL 2 HOUR))
        ")->execute([
            $user['id'],
            $email,
            $token
        ]);

        $link=
        'https://www.jpu.edu.jo/easychair/reset-password?token='
        .$token;

        $subject='EasyChair Password Reset';

        $body='
        <div style="
        font-family:Cairo,Arial;
        background:#f4f7fb;
        padding:40px;
        ">
            <div style="
            max-width:650px;
            margin:auto;
            background:#fff;
            border-radius:20px;
            overflow:hidden;
            box-shadow:0 10px 40px rgba(0,0,0,.08);
            ">

                <div style="
                background:linear-gradient(135deg,#0f4c81,#1b6fd6);
                padding:35px;
                color:#fff;
                text-align:center;
                ">
                    <h1>Password Reset</h1>
                </div>

                <div style="padding:40px">

                    <p>Hello '.$user['first_name'].',</p>

                    <p>
                    We received a request to reset your EasyChair password.
                    </p>

                    <div style="margin:35px 0;text-align:center">

                        <a href="'.$link.'"
                        style="
                        background:#0f4c81;
                        color:#fff;
                        padding:14px 28px;
                        border-radius:12px;
                        text-decoration:none;
                        font-weight:bold;
                        ">
                        Reset Password
                        </a>

                    </div>

                    <p>
                    This link expires in 2 hours.
                    </p>

                </div>

            </div>
        </div>
        ';

        $smtp=new \App\Core\SmtpMailer();

        $smtp->send(
            $email,
            $subject,
            $body,
            $user['first_name'] ?? ''
        );

        header("Location: /easychair/login?reset_sent=1");
        exit;
    }

    public function reset()
    {
        $token=$_GET['token'] ?? '';

        require BASE_PATH.'/app/views/auth/reset_password.php';
    }

    public function update()
    {
        $token=$_POST['token'] ?? '';

        $password=$_POST['password'] ?? '';

        if(strlen($password)<6){
            exit('Password too short');
        }

        $db=Database::getInstance();

        $stmt=$db->prepare("
            SELECT *
            FROM password_reset_tokens
            WHERE token=?
            AND used_at IS NULL
            AND expires_at > NOW()
            ORDER BY id DESC
            LIMIT 1
        ");

        $stmt->execute([$token]);

        $row=$stmt->fetch(\PDO::FETCH_ASSOC);

        if(!$row){
            exit('Invalid or expired token');
        }

        $db->prepare("
            UPDATE users
            SET
            password_hash=?,
            must_change_password=0,
            updated_at=NOW()
            WHERE id=?
        ")->execute([
            password_hash(
                $password,
                PASSWORD_DEFAULT
            ),
            $row['user_id']
        ]);

        $db->prepare("
            UPDATE password_reset_tokens
            SET used_at=NOW()
            WHERE id=?
        ")->execute([
            $row['id']
        ]);

        header("Location: /easychair/login?password_reset=1");
        exit;
    }
}
