<?php
/**
 * Email Mailer Functions
 * Handles sending emails for password reset, notifications, etc.
 */

if (!defined('APP_RUNNING')) {
    die('Direct access not allowed');
}

// Email configuration
define('MAIL_FROM_EMAIL', 'noreply@uhakikimadalali.co.tz');
define('MAIL_FROM_NAME', 'Uhakiki Madalali');
define('MAIL_REPLY_TO', 'support@uhakikimadalali.co.tz');

/**
 * Send email using PHP mail() function
 * For production, consider using PHPMailer or a service like SendGrid
 */
function sendEmail($to, $subject, $body, $isHtml = true) {
    $headers = [];
    $headers[] = 'MIME-Version: 1.0';
    $headers[] = $isHtml ? 'Content-type: text/html; charset=UTF-8' : 'Content-type: text/plain; charset=UTF-8';
    $headers[] = 'From: ' . MAIL_FROM_NAME . ' <' . MAIL_FROM_EMAIL . '>';
    $headers[] = 'Reply-To: ' . MAIL_REPLY_TO;
    $headers[] = 'X-Mailer: PHP/' . phpversion();

    return mail($to, $subject, $body, implode("\r\n", $headers));
}

/**
 * Send password reset email
 */
function sendPasswordResetEmail($email, $fullName, $resetToken, $resetUrl) {
    $subject = 'Password Reset Request - Uhakiki Madalali';

    $body = getEmailTemplate('password_reset', [
        'full_name' => $fullName,
        'reset_url' => $resetUrl,
        'reset_token' => $resetToken,
        'expiry_time' => '1 hour'
    ]);

    return sendEmail($email, $subject, $body);
}

/**
 * Send account approval notification
 */
function sendAccountApprovalEmail($email, $fullName, $status, $reason = '') {
    $subject = $status === 'approved'
        ? 'Account Approved - Uhakiki Madalali'
        : 'Account Status Update - Uhakiki Madalali';

    $body = getEmailTemplate('account_status', [
        'full_name' => $fullName,
        'status' => $status,
        'reason' => $reason,
        'login_url' => APP_URL . '/login'
    ]);

    return sendEmail($email, $subject, $body);
}

/**
 * Get email template
 */
function getEmailTemplate($template, $data = []) {
    $templates = [
        'password_reset' => '
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f6f9;">
    <table width="100%" cellpadding="0" cellspacing="0" style="max-width: 600px; margin: 0 auto; padding: 20px;">
        <tr>
            <td style="background: linear-gradient(135deg, #1a3a6e 0%, #2d5a3d 100%); padding: 30px; text-align: center; border-radius: 10px 10px 0 0;">
                <h1 style="color: white; margin: 0; font-size: 24px;">Uhakiki Madalali</h1>
                <p style="color: rgba(255,255,255,0.8); margin: 10px 0 0 0;">Land Secure</p>
            </td>
        </tr>
        <tr>
            <td style="background: white; padding: 40px; border-radius: 0 0 10px 10px; box-shadow: 0 5px 15px rgba(0,0,0,0.1);">
                <h2 style="color: #1a3a6e; margin-top: 0;">Password Reset Request</h2>
                <p style="color: #666; line-height: 1.6;">Hello {{full_name}},</p>
                <p style="color: #666; line-height: 1.6;">We received a request to reset your password. Click the button below to create a new password:</p>

                <div style="text-align: center; margin: 30px 0;">
                    <a href="{{reset_url}}" style="background: linear-gradient(135deg, #1a3a6e 0%, #2d5a3d 100%); color: white; padding: 15px 40px; text-decoration: none; border-radius: 25px; font-weight: bold; display: inline-block;">Reset Password</a>
                </div>

                <p style="color: #666; line-height: 1.6;">Or copy and paste this link into your browser:</p>
                <p style="background: #f4f6f9; padding: 15px; border-radius: 5px; word-break: break-all; color: #1a3a6e; font-size: 14px;">{{reset_url}}</p>

                <div style="background: #fff3cd; border: 1px solid #ffc107; padding: 15px; border-radius: 5px; margin-top: 20px;">
                    <p style="color: #856404; margin: 0; font-size: 14px;"><strong>Important:</strong> This link will expire in {{expiry_time}}.</p>
                </div>

                <p style="color: #666; line-height: 1.6; margin-top: 20px;">If you did not request a password reset, please ignore this email or contact support if you have concerns.</p>

                <hr style="border: none; border-top: 1px solid #eee; margin: 30px 0;">

                <p style="color: #999; font-size: 12px; text-align: center;">This email was sent by Land Secure.<br>Please do not reply to this email.</p>
            </td>
        </tr>
    </table>
</body>
</html>',

        'account_status' => '
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f6f9;">
    <table width="100%" cellpadding="0" cellspacing="0" style="max-width: 600px; margin: 0 auto; padding: 20px;">
        <tr>
            <td style="background: linear-gradient(135deg, #1a3a6e 0%, #2d5a3d 100%); padding: 30px; text-align: center; border-radius: 10px 10px 0 0;">
                <h1 style="color: white; margin: 0; font-size: 24px;">Uhakiki Madalali</h1>
                <p style="color: rgba(255,255,255,0.8); margin: 10px 0 0 0;">Land Secure</p>
            </td>
        </tr>
        <tr>
            <td style="background: white; padding: 40px; border-radius: 0 0 10px 10px; box-shadow: 0 5px 15px rgba(0,0,0,0.1);">
                <h2 style="color: #1a3a6e; margin-top: 0;">Account Status Update</h2>
                <p style="color: #666; line-height: 1.6;">Hello {{full_name}},</p>

                {{#if_approved}}
                <div style="background: #d4edda; border: 1px solid #28a745; padding: 20px; border-radius: 5px; text-align: center;">
                    <p style="color: #155724; margin: 0; font-size: 18px;"><strong>Your account has been approved!</strong></p>
                </div>
                <p style="color: #666; line-height: 1.6; margin-top: 20px;">You can now log in to your account and start managing your lands.</p>
                <div style="text-align: center; margin: 30px 0;">
                    <a href="{{login_url}}" style="background: linear-gradient(135deg, #1a3a6e 0%, #2d5a3d 100%); color: white; padding: 15px 40px; text-decoration: none; border-radius: 25px; font-weight: bold; display: inline-block;">Login Now</a>
                </div>
                {{/if_approved}}

                {{#if_rejected}}
                <div style="background: #f8d7da; border: 1px solid #dc3545; padding: 20px; border-radius: 5px;">
                    <p style="color: #721c24; margin: 0;"><strong>Your account registration was not approved.</strong></p>
                    {{#if_reason}}<p style="color: #721c24; margin: 10px 0 0 0;">Reason: {{reason}}</p>{{/if_reason}}
                </div>
                <p style="color: #666; line-height: 1.6; margin-top: 20px;">If you believe this is an error, please contact our support team.</p>
                {{/if_rejected}}

                <hr style="border: none; border-top: 1px solid #eee; margin: 30px 0;">

                <p style="color: #999; font-size: 12px; text-align: center;">This email was sent by Land Secure.<br>Please do not reply to this email.</p>
            </td>
        </tr>
    </table>
</body>
</html>'
    ];

    $html = $templates[$template] ?? '';

    // Replace placeholders
    foreach ($data as $key => $value) {
        $html = str_replace('{{' . $key . '}}', htmlspecialchars($value), $html);
    }

    // Handle conditional blocks for account_status template
    if ($template === 'account_status') {
        if ($data['status'] === 'approved') {
            $html = preg_replace('/\{\{#if_approved\}\}(.*?)\{\{\/if_approved\}\}/s', '$1', $html);
            $html = preg_replace('/\{\{#if_rejected\}\}.*?\{\{\/if_rejected\}\}/s', '', $html);
        } else {
            $html = preg_replace('/\{\{#if_rejected\}\}(.*?)\{\{\/if_rejected\}\}/s', '$1', $html);
            $html = preg_replace('/\{\{#if_approved\}\}.*?\{\{\/if_approved\}\}/s', '', $html);
        }

        if (!empty($data['reason'])) {
            $html = preg_replace('/\{\{#if_reason\}\}(.*?)\{\{\/if_reason\}\}/s', '$1', $html);
        } else {
            $html = preg_replace('/\{\{#if_reason\}\}.*?\{\{\/if_reason\}\}/s', '', $html);
        }
    }

    return $html;
}

/**
 * Generate password reset token and save to database
 */
function createPasswordResetToken($conn, $user_id, $email) {
    // Generate secure token
    $token = bin2hex(random_bytes(32));
    $token_hash = hash('sha256', $token);
    $expires_at = date('Y-m-d H:i:s', strtotime('+1 hour'));

    // Delete any existing tokens for this user
    $user_id = intval($user_id);
    mysqli_query($conn, "DELETE FROM password_resets WHERE user_id = $user_id");

    // Insert new token
    $email_escaped = mysqli_real_escape_string($conn, $email);
    $sql = "INSERT INTO password_resets (user_id, email, token_hash, expires_at)
            VALUES ($user_id, '$email_escaped', '$token_hash', '$expires_at')";

    if (mysqli_query($conn, $sql)) {
        return $token; // Return plain token to send in email
    }

    return false;
}

/**
 * Verify password reset token
 */
function verifyPasswordResetToken($conn, $token) {
    $token_hash = hash('sha256', $token);
    $token_hash = mysqli_real_escape_string($conn, $token_hash);

    $sql = "SELECT pr.*, u.username, u.full_name
            FROM password_resets pr
            JOIN users u ON pr.user_id = u.id
            WHERE pr.token_hash = '$token_hash'
            AND pr.expires_at > NOW()
            AND pr.used = 0";

    $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result) === 1) {
        return mysqli_fetch_assoc($result);
    }

    return false;
}

/**
 * Mark password reset token as used
 */
function markPasswordResetTokenUsed($conn, $token) {
    $token_hash = hash('sha256', $token);
    $token_hash = mysqli_real_escape_string($conn, $token_hash);

    return mysqli_query($conn, "UPDATE password_resets SET used = 1 WHERE token_hash = '$token_hash'");
}

/**
 * Clean up expired password reset tokens
 */
function cleanupExpiredTokens($conn) {
    return mysqli_query($conn, "DELETE FROM password_resets WHERE expires_at < NOW() OR used = 1");
}
?>
