<?php
/**
 * Helper Functions
 * CMTC Shopping
 */

// Start session if not started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

/**
 * Get Dynamic Base URL
 * Supports any subfolder (e.g. /u69319090037/shop/ on Host or /shop037.2/ on localhost)
 * @param string $path
 * @return string
 */
function base_url($path = '') {
    static $baseUrl = null;
    if ($baseUrl === null) {
        $scriptName = str_replace('\\', '/', $_SERVER['SCRIPT_NAME'] ?? '');
        
        // Check known subfolder positions
        if (preg_match('#^(.*?)/(views|api|functions|includes)/#', $scriptName, $matches)) {
            $root = rtrim($matches[1], '/');
        } elseif (preg_match('#^(.*?)/[^/]+\.php$#', $scriptName, $matches)) {
            $root = rtrim($matches[1], '/');
        } else {
            $root = '';
        }
        $baseUrl = $root;
    }
    $cleanPath = ltrim($path, '/');
    return $cleanPath === '' ? $baseUrl : ($baseUrl . '/' . $cleanPath);
}

/**
 * Get full URL for product image
 * Supports both filename ('prod_123.jpg') and full relative path ('uploads/products/prod_123.jpg')
 * @param string|null $imagePath
 * @return string
 */
function product_image_url($imagePath) {
    if (empty($imagePath)) {
        return '';
    }
    if (strpos($imagePath, 'http://') === 0 || strpos($imagePath, 'https://') === 0) {
        return $imagePath;
    }
    $clean = ltrim(str_replace('\\', '/', $imagePath), '/');
    if (strpos($clean, 'uploads/') === 0) {
        return base_url($clean);
    }
    return base_url('uploads/products/' . $clean);
}

/**
 * Sanitize output to prevent XSS
 * @param string $str
 * @return string
 */
function sanitize($str) {
    return htmlspecialchars($str ?? '', ENT_QUOTES, 'UTF-8');
}

/**
 * Generate CSRF Token
 * @return string
 */
function get_csrf_token() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

/**
 * Validate CSRF Token
 * @param string $token
 * @return bool
 */
function validate_csrf_token($token) {
    if (empty($_SESSION['csrf_token']) || empty($token)) {
        return false;
    }
    return hash_equals($_SESSION['csrf_token'], $token);
}

/**
 * Format Price to Thai Baht format
 * @param float $price
 * @return string
 */
function format_price($price) {
    return "฿" . number_format($price, 2);
}

/**
 * Format Thai Date
 * @param string $datetime
 * @param bool $include_time
 * @return string
 */
function format_thai_date($datetime, $include_time = true) {
    if (empty($datetime)) return "-";
    $time = strtotime($datetime);
    $months = [
        1 => 'ม.ค.', 2 => 'ก.พ.', 3 => 'มี.ค.', 4 => 'เม.ย.', 
        5 => 'พ.ค.', 6 => 'มิ.ย.', 7 => 'ก.ค.', 8 => 'ส.ค.', 
        9 => 'ก.ย.', 10 => 'ต.ค.', 11 => 'พ.ย.', 12 => 'ธ.ค.'
    ];
    $year = date('Y', $time) + 543;
    $day = date('j', $time);
    $month = $months[intval(date('n', $time))];
    $date_str = "$day $month $year";
    if ($include_time) {
        $date_str .= " " . date('H:i', $time) . " น.";
    }
    return $date_str;
}

/**
 * Write Activity Log
 * @param PDO $db
 * @param string $action
 * @param string $details
 * @return bool
 */
function log_activity($db, $action, $details) {
    try {
        $user_id = $_SESSION['user_id'] ?? null;
        $ip = $_SERVER['REMOTE_ADDR'] ?? '';
        $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
        
        $stmt = $db->prepare("INSERT INTO activity_logs (user_id, action, details, ip_address, user_agent) VALUES (?, ?, ?, ?, ?)");
        return $stmt->execute([$user_id, $action, $details, $ip, $ua]);
    } catch (Exception $e) {
        error_log("Failed to write activity log: " . $e->getMessage());
        return false;
    }
}

/**
 * Check if current user has permission code
 * @param PDO $db
 * @param string $permission_code
 * @return bool
 */
function has_permission($db, $permission_code) {
    if (!isset($_SESSION['role_id'])) {
        return false;
    }
    // Administrator has all permissions (ส่วนแอดมินก็เหมือนเดิม)
    if ($_SESSION['role_id'] == 1) {
        return true;
    }
    // Customers (role_id = 3) can sell items, so they can manage products, stock, and orders.
    if ($_SESSION['role_id'] == 3) {
        return in_array($permission_code, ['manage_orders', 'manage_products', 'manage_stock', 'view_reports']);
    }
    
    try {
        $stmt = $db->prepare("
            SELECT COUNT(*) FROM role_permissions rp 
            JOIN permissions p ON rp.permission_id = p.id 
            WHERE rp.role_id = ? AND p.code = ?
        ");
        $stmt->execute([$_SESSION['role_id'], $permission_code]);
        return $stmt->fetchColumn() > 0;
    } catch (Exception $e) {
        return false;
    }
}

/**
 * Force Authentication
 */
function require_login() {
    if (!isset($_SESSION['user_id'])) {
        header("Location: " . base_url('login.php'));
        exit();
    }
}

/**
 * Force Permission Check
 * @param PDO $db
 * @param string $permission_code
 */
function require_permission($db, $permission_code) {
    require_login();
    if (!has_permission($db, $permission_code)) {
        header("Location: " . base_url('views/403.php'));
        exit();
    }
}

/**
 * Handle Single Secure Image Upload
 * Supports JPG, JPEG, PNG, WEBP, GIF
 * @param array $file $_FILES item
 * @param string $targetSubDir Subfolder inside /uploads/ (e.g. 'products', 'news', 'slips')
 * @param string $prefix File name prefix (e.g. 'prod', 'avatar')
 * @param int $maxSizeBytes Max file size in bytes (default 5MB)
 * @return array ['success' => bool, 'filename' => string, 'url' => string, 'error' => string]
 */
function upload_image($file, $targetSubDir = 'products', $prefix = 'img', $maxSizeBytes = 5242880) {
    if (!isset($file) || $file['error'] !== UPLOAD_ERR_OK) {
        return ['success' => false, 'error' => 'ไม่พบไฟล์หรือเกิดข้อผิดพลาดในการอัปโหลด'];
    }

    if ($file['size'] > $maxSizeBytes) {
        $maxMB = round($maxSizeBytes / (1024 * 1024), 1);
        return ['success' => false, 'error' => "ขนาดไฟล์ใหญ่เกินกำหนด (ไม่เกิน {$maxMB} MB)"];
    }

    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $allowed_exts = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
    if (!in_array($ext, $allowed_exts)) {
        return ['success' => false, 'error' => 'รองรับเฉพาะไฟล์รูปภาพนามสกุล JPG, JPEG, PNG, WEBP, GIF เท่านั้น'];
    }

    // Verify MIME type using finfo or getimagesize
    $tmp_name = $file['tmp_name'];
    $allowed_mimes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
    $is_valid_mime = false;

    if (function_exists('finfo_open')) {
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($finfo, $tmp_name);
        finfo_close($finfo);
        $is_valid_mime = in_array($mime, $allowed_mimes);
    } elseif (function_exists('getimagesize')) {
        $img_info = @getimagesize($tmp_name);
        if ($img_info && in_array($img_info['mime'], $allowed_mimes)) {
            $is_valid_mime = true;
        }
    } else {
        // Fallback to extension check
        $is_valid_mime = true;
    }

    if (!$is_valid_mime) {
        return ['success' => false, 'error' => 'ไฟล์ที่อัปโหลดไม่ใช่รูปภาพที่ถูกต้อง'];
    }

    // Target directory
    $upload_base = dirname(__DIR__) . '/uploads';
    $target_dir = $upload_base . '/' . trim($targetSubDir, '/');
    if (!is_dir($target_dir)) {
        mkdir($target_dir, 0777, true);
    }

    $unique_name = $prefix . '_' . date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
    $target_path = $target_dir . '/' . $unique_name;

    if (move_uploaded_file($tmp_name, $target_path)) {
        $relative_url = 'uploads/' . trim($targetSubDir, '/') . '/' . $unique_name;
        return [
            'success' => true,
            'filename' => $unique_name,
            'relative_path' => $relative_url,
            'url' => base_url($relative_url),
            'error' => ''
        ];
    }

    return ['success' => false, 'error' => 'ไม่สามารถบันทึกไฟล์ลงเซิร์ฟเวอร์ได้'];
}

/**
 * Handle API JSON Response
 * @param bool $success
 * @param string $message
 * @param array $data
 * @param int $code
 */
function api_response($success, $message = '', $data = [], $code = 200) {
    header("Content-Type: application/json; charset=UTF-8");
    http_response_code($code);
    echo json_encode([
        'success' => $success,
        'message' => $message,
        'data' => $data
    ], JSON_UNESCAPED_UNICODE);
    exit();
}
?>
