<?php
require("commonincludefiles.php");

if($_REQUEST["act"] == "getPicture")
{
    $student_id = $_REQUEST["id"];
    $photoname = $_REQUEST["photoname"];
    
    if(empty($photoname))
        $photoname = "default.gif";
    
    $imgfile =$StudentImagePath .$student_id. "/". $photoname;
    
    if(!file_exists($imgfile))
        $imgfile =$StudentImagePath ."default.gif";
    
    echo json_encode(array(
        "success" => true,
        "data" => array(
            "contactId" => $student_id,
            "file" => $imgfile
        )
    ));
}

if($_REQUEST["act"] == "setPicture")
{
    // Validate and sanitize inputs
    $student_id = $_REQUEST["id"]; // Assuming `id` is passed in the request
    
    $thumbimg_path = "";
    $thumbimg = "";
    
    if(isset($_FILES['newPic']['name']) && !empty($_FILES['newPic']['name'])){
        $FileName = $_FILES['newPic']['name'];
        $Ext = strtolower(pathinfo($FileName, PATHINFO_EXTENSION));
        
        $thumbimg = "student_" . $student_id . "." . $Ext;
        $thumbimg_path = $StudentImagePath. $student_id ."/". $thumbimg;
        
        // Delete existing file if it exists
        if(file_exists($thumbimg_path)) {
            unlink($thumbimg_path);
        }
        
        // Create directory if it does not exist
        if (!is_dir($StudentImagePath."/". $student_id."/" )) {
            mkdir($StudentImagePath."/". $student_id. "/", 0755, true); // Recursive directory creation
            chmod($StudentImagePath."/" . $student_id ."/", 0755); // Set appropriate permissions
        }
        
        // Move uploaded file to destination
        move_uploaded_file($_FILES['newPic']['tmp_name'], $thumbimg_path);
        chmod($thumbimg_path, 0644); // Set appropriate permissions
        
        // Example: Resize image if it's an image file (assuming ResizeImageMgmt class exists)
        if (preg_match("/(jpg|gif|png|jpeg)/", $Ext)) {
            $objResizeImage = new ResizeImageMgmt();
            $objResizeImage->resize($thumbimg_path, $SiteImageWidth, $SiteImageHeight, true, true);
        }
        
    } else {
        $thumbimg = "default.gif"; // Default image if no file is uploaded
    }	
		echo "{success:true,data:{student_id:'".$student_id."',file:'".$thumbimg_path."',photoname:'".$thumbimg."'}}";
}
?>