<?php
// app/Helpers/file.php - File Handling Functions

/**
 * Get file icon based on extension
 */
function get_file_icon($filename) {
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    
    $icons = [
        'pdf' => 'fas fa-file-pdf text-danger',
        'doc' => 'fas fa-file-word text-primary',
        'docx' => 'fas fa-file-word text-primary',
        'xls' => 'fas fa-file-excel text-success',
        'xlsx' => 'fas fa-file-excel text-success',
        'ppt' => 'fas fa-file-powerpoint text-warning',
        'pptx' => 'fas fa-file-powerpoint text-warning',
        'zip' => 'fas fa-file-archive text-secondary',
        'rar' => 'fas fa-file-archive text-secondary',
        'jpg' => 'fas fa-file-image text-info',
        'jpeg' => 'fas fa-file-image text-info',
        'png' => 'fas fa-file-image text-info',
        'gif' => 'fas fa-file-image text-info',
        'txt' => 'fas fa-file-alt text-secondary',
        'csv' => 'fas fa-file-csv text-success',
    ];
    
    return $icons[$ext] ?? 'fas fa-file text-secondary';
}

/**
 * Check if file is an image
 */
function is_image_file($filename) {
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    $image_extensions = explode(',', ALLOWED_IMAGE_TYPES);
    return in_array($ext, $image_extensions);
}

/**
 * Check if file is a document
 */
function is_document_file($filename) {
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    $doc_extensions = explode(',', ALLOWED_DOCUMENT_TYPES);
    return in_array($ext, $doc_extensions);
}

/**
 * Get mime type from file
 */
function get_mime_type($file_path) {
    if (!file_exists($file_path)) {
        return 'application/octet-stream';
    }
    
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $file_path);
    finfo_close($finfo);
    
    return $mime;
}

/**
 * Download file
 */
function download_file($file_path, $filename = null) {
    $full_path = UPLOAD_PATH . '/' . ltrim($file_path, '/');
    
    if (!file_exists($full_path)) {
        die('File not found');
    }
    
    $filename = $filename ?: basename($full_path);
    
    header('Content-Type: ' . get_mime_type($full_path));
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Length: ' . filesize($full_path));
    header('Cache-Control: no-cache, must-revalidate');
    header('Expires: 0');
    
    readfile($full_path);
    exit;
}

/**
 * Get file URL
 */
function file_url($path) {
    if (empty($path)) {
        return asset('images/placeholder.png');
    }
    return upload($path);
}

/**
 * Create directory if not exists
 */
function ensure_directory($path) {
    if (!is_dir($path)) {
        return mkdir($path, 0755, true);
    }
    return true;
}

/**
 * Get directory size
 */
function get_directory_size($path) {
    $size = 0;
    
    if (!is_dir($path)) {
        return 0;
    }
    
    foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $file) {
        if ($file->isFile()) {
            $size += $file->getSize();
        }
    }
    
    return $size;
}

/**
 * Clean directory (remove old files)
 */
function clean_directory($path, $days_old = 30) {
    if (!is_dir($path)) {
        return false;
    }
    
    $deleted = 0;
    $cutoff = time() - ($days_old * 24 * 60 * 60);
    
    $files = glob($path . '/*');
    foreach ($files as $file) {
        if (is_file($file) && filemtime($file) < $cutoff) {
            if (unlink($file)) {
                $deleted++;
            }
        }
    }
    
    return $deleted;
}

/**
 * Get file created date
 */
function get_file_date($file_path, $format = 'M d, Y') {
    $full_path = UPLOAD_PATH . '/' . ltrim($file_path, '/');
    
    if (!file_exists($full_path)) {
        return 'N/A';
    }
    
    return date($format, filemtime($full_path));
}

/**
 * Copy file
 */
function copy_file($source, $destination) {
    $source_path = UPLOAD_PATH . '/' . ltrim($source, '/');
    $dest_path = UPLOAD_PATH . '/' . ltrim($destination, '/');
    
    // Create destination directory if needed
    $dest_dir = dirname($dest_path);
    if (!is_dir($dest_dir)) {
        mkdir($dest_dir, 0755, true);
    }
    
    return copy($source_path, $dest_path);
}

/**
 * Move file
 */
function move_file($source, $destination) {
    $source_path = UPLOAD_PATH . '/' . ltrim($source, '/');
    $dest_path = UPLOAD_PATH . '/' . ltrim($destination, '/');
    
    // Create destination directory if needed
    $dest_dir = dirname($dest_path);
    if (!is_dir($dest_dir)) {
        mkdir($dest_dir, 0755, true);
    }
    
    return rename($source_path, $dest_path);
}

/**
 * Get image dimensions
 */
function get_image_dimensions($file_path) {
    $full_path = UPLOAD_PATH . '/' . ltrim($file_path, '/');
    
    if (!file_exists($full_path) || !is_image_file($file_path)) {
        return null;
    }
    
    $info = getimagesize($full_path);
    
    if (!$info) {
        return null;
    }
    
    return [
        'width' => $info[0],
        'height' => $info[1],
        'type' => $info[2],
        'mime' => $info['mime']
    ];
}

/**
 * Create thumbnail
 */
function create_thumbnail($file_path, $width = 300, $height = 300) {
    $full_path = UPLOAD_PATH . '/' . ltrim($file_path, '/');
    
    if (!file_exists($full_path) || !is_image_file($file_path)) {
        return false;
    }
    
    $info = getimagesize($full_path);
    if (!$info) return false;
    
    list($orig_width, $orig_height, $type) = $info;
    
    // Create image resource
    switch ($type) {
        case IMAGETYPE_JPEG:
            $source = imagecreatefromjpeg($full_path);
            break;
        case IMAGETYPE_PNG:
            $source = imagecreatefrompng($full_path);
            break;
        case IMAGETYPE_GIF:
            $source = imagecreatefromgif($full_path);
            break;
        default:
            return false;
    }
    
    // Calculate thumbnail dimensions
    $ratio = min($width / $orig_width, $height / $orig_height);
    $thumb_width = $orig_width * $ratio;
    $thumb_height = $orig_height * $ratio;
    
    // Create thumbnail
    $thumbnail = imagecreatetruecolor($thumb_width, $thumb_height);
    
    // Preserve transparency
    if ($type == IMAGETYPE_PNG || $type == IMAGETYPE_GIF) {
        imagealphablending($thumbnail, false);
        imagesavealpha($thumbnail, true);
        $transparent = imagecolorallocatealpha($thumbnail, 255, 255, 255, 127);
        imagefilledrectangle($thumbnail, 0, 0, $thumb_width, $thumb_height, $transparent);
    }
    
    imagecopyresampled($thumbnail, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $orig_width, $orig_height);
    
    // Save thumbnail
    $path_info = pathinfo($full_path);
    $thumb_path = $path_info['dirname'] . '/thumb_' . $path_info['basename'];
    
    switch ($type) {
        case IMAGETYPE_JPEG:
            imagejpeg($thumbnail, $thumb_path, 85);
            break;
        case IMAGETYPE_PNG:
            imagepng($thumbnail, $thumb_path, 8);
            break;
        case IMAGETYPE_GIF:
            imagegif($thumbnail, $thumb_path);
            break;
    }
    
    imagedestroy($source);
    imagedestroy($thumbnail);
    
    // Return relative path
    return str_replace(UPLOAD_PATH . '/', '', $thumb_path);
}

/**
 * Read file contents
 */
function read_file($file_path) {
    $full_path = UPLOAD_PATH . '/' . ltrim($file_path, '/');
    
    if (!file_exists($full_path)) {
        return null;
    }
    
    return file_get_contents($full_path);
}

/**
 * Write to file
 */
function write_file($file_path, $content) {
    $full_path = UPLOAD_PATH . '/' . ltrim($file_path, '/');
    
    // Create directory if needed
    $dir = dirname($full_path);
    if (!is_dir($dir)) {
        mkdir($dir, 0755, true);
    }
    
    return file_put_contents($full_path, $content) !== false;
}

/**
 * Append to file
 */
function append_file($file_path, $content) {
    $full_path = UPLOAD_PATH . '/' . ltrim($file_path, '/');
    
    // Create directory if needed
    $dir = dirname($full_path);
    if (!is_dir($dir)) {
        mkdir($dir, 0755, true);
    }
    
    return file_put_contents($full_path, $content, FILE_APPEND) !== false;
}


/**
 * Convert timestamp to "time ago" format
 * Example: "2 hours ago", "3 days ago", etc.
 */
if (!function_exists('time_ago')) {
    function time_ago($datetime) {
        if (empty($datetime)) {
            return 'N/A';
        }
        
        $timestamp = strtotime($datetime);
        $difference = time() - $timestamp;
        
        if ($difference < 0) {
            return 'just now';
        }
        
        if ($difference < 60) {
            return 'just now';
        } elseif ($difference < 3600) {
            $minutes = floor($difference / 60);
            return $minutes . ' minute' . ($minutes > 1 ? 's' : '') . ' ago';
        } elseif ($difference < 86400) {
            $hours = floor($difference / 3600);
            return $hours . ' hour' . ($hours > 1 ? 's' : '') . ' ago';
        } elseif ($difference < 604800) {
            $days = floor($difference / 86400);
            return $days . ' day' . ($days > 1 ? 's' : '') . ' ago';
        } elseif ($difference < 2592000) {
            $weeks = floor($difference / 604800);
            return $weeks . ' week' . ($weeks > 1 ? 's' : '') . ' ago';
        } elseif ($difference < 31536000) {
            $months = floor($difference / 2592000);
            return $months . ' month' . ($months > 1 ? 's' : '') . ' ago';
        } else {
            $years = floor($difference / 31536000);
            return $years . ' year' . ($years > 1 ? 's' : '') . ' ago';
        }
    }
}