<?php
function cropStudentPhoto($source_path, $target_path, $width = 400, $height = 500) {
    list($src_w, $src_h, $type) = getimagesize($source_path);
    
    // Create image resource based on type
    switch ($type) {
        case IMAGETYPE_JPEG: $src_img = imagecreatefromjpeg($source_path); break;
        case IMAGETYPE_PNG:  $src_img = imagecreatefrompng($source_path); break;
        default: return false;
    }

    $target_ratio = $width / $height;
    $current_ratio = $src_w / $src_h;

    if ($current_ratio > $target_ratio) {
        // Image is too wide
        $crop_w = $src_h * $target_ratio;
        $crop_h = $src_h;
        $src_x = ($src_w - $crop_w) / 2;
        $src_y = 0;
    } else {
        // Image is too tall
        $crop_w = $src_w;
        $crop_h = $src_w / $target_ratio;
        $src_x = 0;
        $src_y = ($src_h - $crop_h) / 2;
    }

    // Create the 400x500 canvas
    $dst_img = imagecreatetruecolor($width, $height);
    
    // Perform the crop and resize
    imagecopyresampled($dst_img, $src_img, 0, 0, $src_x, $src_y, $width, $height, $crop_w, $crop_h);

    // Save as JPG with high quality
    imagejpeg($dst_img, $target_path, 90);

    // Free memory
    imagedestroy($src_img);
    imagedestroy($dst_img);
    return true;
}
?>