<?php
// This file contains all globally used helper functions for the website.

// Required for PHPMailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Manually include the core PHPMailer files to bypass any autoloader issues.
require_once __DIR__ . '/../vendor/PHPMailer/src/Exception.php';
require_once __DIR__ . '/../vendor/PHPMailer/src/PHPMailer.php';
require_once __DIR__ . '/../vendor/PHPMailer/src/SMTP.php';

if (!function_exists('send_email')) {
    /**
     * Sends an email using PHPMailer with SMTP settings from the database.
     */
    function send_email($recipient_email, $subject, $body, $recipient_name = '') {
        global $conn;
        $settings_result = $conn->query("SELECT setting_name, setting_value FROM site_settings WHERE setting_name LIKE 'smtp_%'");
        $mail_settings = [];
        while ($row = $settings_result->fetch_assoc()) {
            $mail_settings[$row['setting_name']] = $row['setting_value'];
        }

        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host       = $mail_settings['smtp_host'] ?? '';
            $mail->SMTPAuth   = true;
            $mail->Username   = $mail_settings['smtp_username'] ?? '';
            $mail->Password   = $mail_settings['smtp_password'] ?? '';
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port       = $mail_settings['smtp_port'] ?? 587;
            $mail->setFrom($mail_settings['smtp_from_email'] ?? 'from@example.com', $mail_settings['smtp_from_name'] ?? 'Support');
            $mail->addAddress($recipient_email, $recipient_name);
            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body    = $body;
            $mail->AltBody = strip_tags($body);
            $mail->send();
            return true;
        } catch (Exception $e) {
            error_log("Mailer Error: {$mail->ErrorInfo}");
            return false;
        }
    }
}

if (!function_exists('get_exchange_rates')) {
    /**
     * Fetches all active currencies and their exchange rates from the database.
     */
    function get_exchange_rates() {
        global $conn;
        static $rates = null;
        if ($rates === null) {
            $rates = [];
            if ($result = $conn->query("SELECT code, symbol, exchange_rate FROM currencies WHERE is_active = 1")) {
                while ($row = $result->fetch_assoc()) {
                    $rates[$row['code']] = ['symbol' => $row['symbol'], 'rate' => (float)$row['exchange_rate']];
                }
            }
        }
        return $rates;
    }
}

if (!function_exists('format_price')) {
    /**
     * Formats a price based on the user's selected currency.
     */
    function format_price($base_price) {
        global $conn;
        static $default_currency = 'PHP';
        $rates = get_exchange_rates();
        static $is_default_fetched = false;
        if (!$is_default_fetched) {
            if ($settings_result = $conn->query("SELECT setting_value FROM site_settings WHERE setting_name = 'site_base_currency' LIMIT 1")) {
                $default_currency = $settings_result->fetch_assoc()['setting_value'] ?? 'PHP';
            }
            $is_default_fetched = true;
        }
        $current_currency = $_SESSION['currency'] ?? $default_currency;
        if (isset($rates[$current_currency])) {
            $symbol = $rates[$current_currency]['symbol'];
            $rate = $rates[$current_currency]['rate'];
            $converted_price = $base_price * $rate;
            return $symbol . number_format($converted_price, 2);
        }
        $default_symbol = $rates[$default_currency]['symbol'] ?? '₱';
        return $default_symbol . number_format($base_price, 2);
    }
}

if (!function_exists('get_booking_style')) {
    /**
     * Returns a consistent Bootstrap icon and color class for different booking types.
     */
    function get_booking_style($type) {
        switch ($type) {
            case 'Tour': return ['icon' => 'bi-geo-alt-fill', 'color' => 'primary'];
            case 'Hotel': return ['icon' => 'bi-building', 'color' => 'success'];
            case 'Flight': return ['icon' => 'bi-airplane-fill', 'color' => 'info'];
            case 'Ferry': return ['icon' => 'bi-tsunami', 'color' => 'warning'];
            default: return ['icon' => 'bi-briefcase-fill', 'color' => 'secondary'];
        }
    }
}

if (!function_exists('get_transaction_style')) {
    /**
     * Returns a consistent Bootstrap icon and color class for different wallet transaction types.
     */
    function get_transaction_style($type) {
        switch ($type) {
            case 'Deposit': return ['icon' => 'bi-arrow-down-circle-fill', 'color' => 'success'];
            case 'Refund': return ['icon' => 'bi-arrow-counterclockwise', 'color' => 'info'];
            case 'Payment': return ['icon' => 'bi-cart-dash-fill', 'color' => 'danger'];
            case 'Withdrawal': return ['icon' => 'bi-arrow-up-circle-fill', 'color' => 'warning'];
            default: return ['icon' => 'bi-question-circle-fill', 'color' => 'secondary'];
        }
    }
}

if (!function_exists('time_ago')) {
    /**
     * Converts a timestamp into a human-readable "time ago" string.
     */
    function time_ago($datetime) {
        if ($datetime === null) return '';
        $time = strtotime($datetime);
        $diff = time() - $time;
        if ($diff < 1) { return 'just now'; }
        $a = [31536000 => 'year', 2592000 => 'month', 604800 => 'week', 86400 => 'day', 3600 => 'hour', 60 => 'minute', 1 => 'second'];
        foreach ($a as $secs => $str) {
            $d = $diff / $secs;
            if ($d >= 1) {
                $r = round($d);
                return $r . ' ' . $str . ($r > 1 ? 's' : '') . ' ago';
            }
        }
    }
}

if (!function_exists('display_verified_badge')) {
    /**
     * Displays a "Verified Partner" badge if the partner is verified.
     */
    function display_verified_badge($is_verified) {
        if ($is_verified) {
            echo '<span class="badge bg-primary"><i class="bi bi-patch-check-fill me-1"></i>Verified Partner</span>';
        }
    }
}



// In includes/helpers.php

if (!function_exists('handle_admin_avatar_upload')) {
    /**
     * Handles uploading and resizing an admin's profile picture.
     *
     * @param string $file_input_name The name of the file input field.
     * @param int $admin_id The ID of the admin to update.
     * @return bool True on success, false on failure.
     */
    function handle_admin_avatar_upload($file_input_name, $admin_id) {
        global $conn;
        if (isset($_FILES[$file_input_name]) && $_FILES[$file_input_name]['error'] === UPLOAD_ERR_OK) {
            $file = $_FILES[$file_input_name];
            $upload_dir = '../uploads/avatars/';
            if (!is_dir($upload_dir)) { mkdir($upload_dir, 0755, true); }
            
            $filename = 'admin-' . $admin_id . '-' . time() . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
            $target_path = $upload_dir . $filename;
            
            if (move_uploaded_file($file['tmp_name'], $target_path)) {
                $db_path = 'uploads/avatars/' . $filename;
                $stmt = $conn->prepare("UPDATE admins SET profile_image_url = ? WHERE id = ?");
                $stmt->bind_param("si", $db_path, $admin_id);
                $stmt->execute();
                $stmt->close();
                return true;
            }
        }
        return false;
    }
}
