<?php
/**
 * OTP Handler Class
 * Manages OTP generation, sending via email, and verification
 */

require_once 'config.php';
require_once 'PHPMailer-master/src/PHPMailer.php';
require_once 'PHPMailer-master/src/SMTP.php';
require_once 'PHPMailer-master/src/Exception.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

class OTPHandler {
    private $conn;
    
    public function __construct($database) {
        $this->conn = $database;
    }
    
    /**
     * Generate random OTP
     */
    public function generateOTP() {
        return str_pad(random_int(0, pow(10, OTP_LENGTH) - 1), OTP_LENGTH, '0', STR_PAD_LEFT);
    }
    
    /**
     * Send OTP via Email
     */
    public function sendOTPEmail($email, $otp, $type = 'registration') {
        try {
            $mail = new PHPMailer(true);
            
            // Server settings
            $mail->isSMTP();
            $mail->Host = MAIL_HOST;
            $mail->SMTPAuth = true;
            $mail->Username = MAIL_USERNAME;
            $mail->Password = MAIL_PASSWORD;
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = MAIL_PORT;
            $mail->SMTPOptions = array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                )
            );
            
            // Recipients
            $mail->setFrom(MAIL_USERNAME, MAIL_FROM_NAME);
            $mail->addAddress($email);
            
            // Content
            $mail->isHTML(true);
            
            if ($type === 'registration') {
                $mail->Subject = 'Email Verification - Your OTP Code';
                $mail->Body = $this->getRegistrationEmailTemplate($otp);
            } else if ($type === 'password_reset') {
                $mail->Subject = 'Password Reset - Your OTP Code';
                $mail->Body = $this->getPasswordResetEmailTemplate($otp);
            }
            
            if (!$mail->send()) {
                error_log("Email Send Failed for: " . $email . " | Error: " . $mail->ErrorInfo);
                return false;
            }
            return true;
        } catch (Exception $e) {
            error_log("PHPMailer Exception: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Registration email template
     */
    private function getRegistrationEmailTemplate($otp) {
        return "
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; background-color: #f4f4f4; }
                .container { max-width: 600px; margin: 20px auto; background-color: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
                .header { background-color: #4CAF50; color: white; padding: 20px; text-align: center; border-radius: 8px 8px 0 0; }
                .content { padding: 20px; }
                .otp-code { font-size: 32px; font-weight: bold; color: #4CAF50; text-align: center; letter-spacing: 10px; margin: 20px 0; }
                .footer { text-align: center; color: #888; font-size: 12px; margin-top: 20px; border-top: 1px solid #eee; padding-top: 20px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h2>Welcome to Cleaning Service</h2>
                </div>
                <div class='content'>
                    <p>Hello,</p>
                    <p>Thank you for registering with us! To complete your registration, please verify your email using the code below:</p>
                    <div class='otp-code'>$otp</div>
                    <p style='color: #666;'>This code will expire in " . OTP_EXPIRY_MINUTES . " minutes.</p>
                    <p>If you did not request this code, please ignore this email.</p>
                </div>
                <div class='footer'>
                    <p>&copy; 2024 Cleaning Service. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>";
    }
    
    /**
     * Password reset email template
     */
    private function getPasswordResetEmailTemplate($otp) {
        return "
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; background-color: #f4f4f4; }
                .container { max-width: 600px; margin: 20px auto; background-color: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
                .header { background-color: #FF9800; color: white; padding: 20px; text-align: center; border-radius: 8px 8px 0 0; }
                .content { padding: 20px; }
                .otp-code { font-size: 32px; font-weight: bold; color: #FF9800; text-align: center; letter-spacing: 10px; margin: 20px 0; }
                .footer { text-align: center; color: #888; font-size: 12px; margin-top: 20px; border-top: 1px solid #eee; padding-top: 20px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h2>Password Reset Request</h2>
                </div>
                <div class='content'>
                    <p>Hello,</p>
                    <p>We received a request to reset your password. Use the verification code below to proceed:</p>
                    <div class='otp-code'>$otp</div>
                    <p style='color: #666;'>This code will expire in " . OTP_EXPIRY_MINUTES . " minutes.</p>
                    <p style='color: #d32f2f;'><strong>Security Notice:</strong> If you did not request a password reset, please ignore this email.</p>
                </div>
                <div class='footer'>
                    <p>&copy; 2024 Cleaning Service. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>";
    }
    
    /**
     * Store OTP in database
     */
    public function storeOTP($email, $otp, $type = 'registration') {
        // Create table if it doesn't exist
        $createTableSQL = "CREATE TABLE IF NOT EXISTS otp_verifications (
            id INT PRIMARY KEY AUTO_INCREMENT,
            email VARCHAR(255) NOT NULL,
            otp VARCHAR(10) NOT NULL,
            type ENUM('registration', 'password_reset') DEFAULT 'registration',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            expires_at TIMESTAMP NOT NULL,
            verified BOOLEAN DEFAULT FALSE
        )";
        
        if (!$this->conn->query($createTableSQL)) {
            error_log("Error creating otp_verifications table: " . $this->conn->error);
        }
        
        // Delete expired and verified OTPs for this email
        $deleteSQL = "DELETE FROM otp_verifications WHERE email = ? AND (expires_at < NOW() OR verified = TRUE)";
        $stmt = $this->conn->prepare($deleteSQL);
        if ($stmt) {
            $stmt->bind_param('s', $email);
            $stmt->execute();
            $stmt->close();
        }
        
        // Insert new OTP
        $expiryTime = OTP_EXPIRY_MINUTES;
        $insertSQL = "INSERT INTO otp_verifications (email, otp, type, expires_at) VALUES (?, ?, ?, DATE_ADD(NOW(), INTERVAL ? MINUTE))";
        $stmt = $this->conn->prepare($insertSQL);
        if (!$stmt) {
            error_log("Error preparing insert statement: " . $this->conn->error);
            return false;
        }
        $stmt->bind_param('sssi', $email, $otp, $type, $expiryTime);
        
        $result = $stmt->execute();
        if (!$result) {
            error_log("Error executing insert: " . $stmt->error);
        }
        $stmt->close();
        return $result;
    }
    
    /**
     * Verify OTP
     */
    public function verifyOTP($email, $otp, $type = 'registration') {
        $query = "SELECT id FROM otp_verifications WHERE email = ? AND otp = ? AND type = ? AND verified = FALSE AND expires_at > NOW()";
        
        $stmt = $this->conn->prepare($query);
        if (!$stmt) {
            error_log("Error in verifyOTP prepare: " . $this->conn->error);
            return false;
        }
        
        $stmt->bind_param('sss', $email, $otp, $type);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            // Mark OTP as verified
            $updateSQL = "UPDATE otp_verifications SET verified = TRUE WHERE email = ? AND otp = ? AND type = ?";
            $updateStmt = $this->conn->prepare($updateSQL);
            $updateStmt->bind_param('sss', $email, $otp, $type);
            $updateStmt->execute();
            $updateStmt->close();
            
            $stmt->close();
            return true;
        }
        
        $stmt->close();
        return false;
    }
    
    /**
     * Resend OTP
     */
    public function resendOTP($email, $type = 'registration') {
        // Generate new OTP
        $otp = $this->generateOTP();
        
        // Store OTP
        if ($this->storeOTP($email, $otp, $type)) {
            // Send email
            return $this->sendOTPEmail($email, $otp, $type);
        }
        
        return false;
    }
}
?>
