<?php
require_once 'config.php';
require_once 'db.php';

// Ensure upload directories exist
function createUploadDirs() {
    if (!file_exists(FS_COMPRESSED)) {
        mkdir(FS_COMPRESSED, 0755, true);
    }
    if (!file_exists(FS_THUMBNAILS)) {
        mkdir(FS_THUMBNAILS, 0755, true);
    }
}
// Image Processing Functions
function compressImage($source, $destination) {
    createUploadDirs(); // Ensure directories exist
    
    $info = getimagesize($source);
    if (!$info) {
        throw new Exception("Invalid image file");
    }

    switch($info['mime']) {
        case 'image/jpeg':
            $image = imagecreatefromjpeg($source);
            break;
        case 'image/png':
            $image = imagecreatefrompng($source);
            break;
        default:
            throw new Exception("Unsupported image type: ".$info['mime']);
    }

    if (!$image) {
        throw new Exception("Failed to create image resource");
    }

    // Resize logic
    $width = imagesx($image);
    $height = imagesy($image);
    
    if($width > MAX_WIDTH) {
        $newWidth = MAX_WIDTH;
        $newHeight = (int) ($height * (MAX_WIDTH / $width));
        $resized = imagescale($image, $newWidth, $newHeight);
        imagedestroy($image);
        $image = $resized;
    }

    // Save compressed
    if (!imagejpeg($image, $destination, 75)) {
        imagedestroy($image);
        throw new Exception("Failed to save compressed image");
    }
    imagedestroy($image);
    
    return $destination;
}

function createThumbnail($sourcePath, $destPath) {
    createUploadDirs(); // Ensure directories exist
    
    if (!file_exists($sourcePath)) {
        throw new Exception("Source image not found: $sourcePath");
    }

    $image = imagecreatefromjpeg($sourcePath);
    if (!$image) {
        throw new Exception("Failed to create image resource from $sourcePath");
    }

    $width = imagesx($image);
    $height = imagesy($image);
    
    $size = min($width, $height);
    $thumb = imagecreatetruecolor(THUMBNAIL_SIZE, THUMBNAIL_SIZE);
    
    imagecopyresampled($thumb, $image,
        0, 0, 
        ($width - $size)/2, ($height - $size)/2,
        THUMBNAIL_SIZE, THUMBNAIL_SIZE,
        $size, $size
    );
    
    if (!imagejpeg($thumb, $destPath, 85)) {
        imagedestroy($thumb);
        throw new Exception("Failed to save thumbnail");
    }
    imagedestroy($thumb);
}

// Patient and Session Management
function createPatient($guestCode) {
    global $pdo;
    try {
        $stmt = $pdo->prepare("INSERT INTO patients (guest_code) VALUES (?)");
        $stmt->execute([$guestCode]);
        return $pdo->lastInsertId();
    } catch(PDOException $e) {
        if($e->errorInfo[1] == 1062) { // Duplicate entry
            $stmt = $pdo->prepare("SELECT id FROM patients WHERE guest_code = ?");
            $stmt->execute([$guestCode]);
            return $stmt->fetchColumn();
        }
        throw $e;
    }
}

function createSession($patientId, $treatmentId, $sessionNumber) {
    global $pdo;
    try {
        $stmt = $pdo->prepare("
            INSERT INTO sessions 
            (patient_id, treatment_id, session_number, session_date)
            VALUES (?, ?, ?, CURDATE())
        ");
        $stmt->execute([$patientId, $treatmentId, $sessionNumber]);
        return $pdo->lastInsertId();
    } catch(PDOException $e) {
        throw new Exception("Session creation failed: " . $e->getMessage());
    }
}

// Image Upload Handling
function processUploadedImages($sessionId, $type, $patientId = null) {
    global $pdo;
    if (empty($_FILES[$type . '_images']['tmp_name']) || empty(array_filter($_FILES[$type . '_images']['tmp_name']))) {
    return;
    }
    // Create a special session for before treatment if patientId is provided
    /*(if ($type === 'before' && $patientId) {
        // createSession(patient_id, session_number, is_after_treatment)
        $sessionId = createSession($patientId, null, 0); // 0 indicates 'before treatment'
    }  **/

    if (empty($_FILES[$type . '_images']['tmp_name'])) {
        return;
    }

    foreach ($_FILES[$type . '_images']['tmp_name'] as $index => $tmpPath) {
        if (!empty($tmpPath)) {
            try {
                // Get angle from form data
                $angle = $_POST[$type . '_angle'][$index] ?? 'front';

                // Generate unique filename
                $filename = uniqid() . '_' . basename($_FILES[$type . '_images']['name'][$index]);
                
                //$compressedPath = UPLOAD_COMPRESSED . $filename;
                //$thumbnailPath = UPLOAD_THUMBNAILS . $filename;
                // Store only relative paths
                $compressedPath = FS_COMPRESSED . $filename;
                $thumbnailPath = FS_THUMBNAILS . $filename;

                // Process images
                compressImage($tmpPath, $compressedPath);
                createThumbnail($compressedPath, $thumbnailPath);

                // Store in database
                $stmt = $pdo->prepare("
                    INSERT INTO photos 
                    (session_id, type, image_path, thumbnail_path, face_angle)
                    VALUES (?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $sessionId,
                    $type,
                    $filename,
                    $filename,
                    $angle
                ]);
            } catch (Exception $e) {
                error_log("Image processing error: " . $e->getMessage());
                throw new Exception("Failed to process " . $type . " image: " . $e->getMessage());
            }
        }
    }
}
?>