<?php
// Start session
session_start();

// Include database connection
require_once "../config/connection.php";

// Set content type to JSON
header('Content-Type: application/json');

// Check if user is logged in and is borrower
if (!is_logged_in() || !is_user_type('borrower')) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

// Get POST data
$item_id = isset($_POST['item_id']) ? intval($_POST['item_id']) : 0;
$condition = isset($_POST['condition']) ? trim($_POST['condition']) : '';
$notes = isset($_POST['notes']) ? trim($_POST['notes']) : '';
$condition_photo = isset($_POST['condition_photo']) ? $_POST['condition_photo'] : '';
$placement_photo = isset($_POST['placement_photo']) ? $_POST['placement_photo'] : '';

// Validate input
if (!$item_id || !$condition || !$condition_photo || !$placement_photo) {
    echo json_encode(['success' => false, 'message' => 'Data tidak lengkap']);
    exit();
}

// Validate condition
$valid_conditions = ['baik', 'rusak', 'hilang'];
if (!in_array($condition, $valid_conditions)) {
    echo json_encode(['success' => false, 'message' => 'Kondisi tidak valid']);
    exit();
}

// Validate photo data (should be base64)
if (!preg_match('/^data:image\/(jpeg|jpg|png);base64,/', $condition_photo)) {
    echo json_encode(['success' => false, 'message' => 'Format foto kondisi tidak valid']);
    exit();
}

if (!preg_match('/^data:image\/(jpeg|jpg|png);base64,/', $placement_photo)) {
    echo json_encode(['success' => false, 'message' => 'Format foto penempatan tidak valid']);
    exit();
}

// Function to compress and optimize image
function optimizeImage($base64Image, $maxWidth = 800, $quality = 80) {
    try {
        // Extract image data
        $imageData = explode(',', $base64Image);
        if (count($imageData) != 2) {
            return $base64Image; // Return original if can't process
        }
        
        $imageString = base64_decode($imageData[1]);
        $image = imagecreatefromstring($imageString);
        
        if (!$image) {
            return $base64Image; // Return original if can't create image
        }
        
        $originalWidth = imagesx($image);
        $originalHeight = imagesy($image);
        
        // Calculate new dimensions
        if ($originalWidth > $maxWidth) {
            $ratio = $maxWidth / $originalWidth;
            $newWidth = $maxWidth;
            $newHeight = intval($originalHeight * $ratio);
            
            // Create new image
            $newImage = imagecreatetruecolor($newWidth, $newHeight);
            imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
            
            // Save as JPEG
            ob_start();
            imagejpeg($newImage, null, $quality);
            $optimizedImageString = ob_get_contents();
            ob_end_clean();
            
            // Clean up
            imagedestroy($image);
            imagedestroy($newImage);
            
            return 'data:image/jpeg;base64,' . base64_encode($optimizedImageString);
        }
        
        // If image is already small enough, just convert to JPEG if needed
        ob_start();
        imagejpeg($image, null, $quality);
        $optimizedImageString = ob_get_contents();
        ob_end_clean();
        
        imagedestroy($image);
        
        return 'data:image/jpeg;base64,' . base64_encode($optimizedImageString);
        
    } catch (Exception $e) {
        error_log("Image optimization error: " . $e->getMessage());
        return $base64Image; // Return original if optimization fails
    }
}

try {
    // Start transaction
    $conn->begin_transaction();
    
    // Get transaction item details and verify ownership
    $item_stmt = $conn->prepare("
        SELECT 
            ti.*,
            st.borrower_id,
            st.tanggal_pengembalian,
            st.status_peminjaman,
            st.reservation_number,
            csi.id as stock_id,
            csi.component_id,
            csi.color_id,
            csi.kode_barang,
            csi.rack_no,
            csi.lokasi,
            mcp.code_color,
            cc.component_name,
            b.nama_buyer
        FROM transaction_items_semarang ti
        JOIN stock_transactions_semarang st ON ti.transaction_id = st.id
        JOIN color_stock_items_semarang csi ON ti.stock_item_id = csi.id
        JOIN master_color_panel_semarang mcp ON csi.color_id = mcp.id
        JOIN color_components_semarang cc ON csi.component_id = cc.id
        JOIN buyers_semarang b ON mcp.buyer_id = b.id
        WHERE ti.id = ? AND st.borrower_id = ? AND ti.dikembalikan = 0
    ");
    $item_stmt->bind_param("ii", $item_id, $_SESSION['user_id']);
    $item_stmt->execute();
    $item_result = $item_stmt->get_result();
    
    if ($item_result->num_rows == 0) {
        throw new Exception('Item tidak ditemukan atau sudah dikembalikan');
    }
    
    $item = $item_result->fetch_assoc();
    $item_stmt->close();
    
    // Calculate time status
    $current_time = new DateTime();
    $return_deadline = new DateTime($item['tanggal_pengembalian']);
    $tolerance_deadline = clone $return_deadline;
    $tolerance_deadline->add(new DateInterval('PT15M')); // Add 15 minutes tolerance
    
    $status_waktu = 'tepat';
    if ($current_time > $tolerance_deadline) {
        $status_waktu = 'overdue';
    }
    
    // Optimize images before storing
    $optimized_condition_photo = optimizeImage($condition_photo);
    $optimized_placement_photo = optimizeImage($placement_photo);
    
    // Update transaction item with optimized photos
    $update_item_stmt = $conn->prepare("
        UPDATE transaction_items_semarang 
        SET dikembalikan = 1,
            tanggal_kembali = NOW(),
            kondisi_kembali = ?,
            catatan = ?,
            foto_bukti = ?,
            foto_pengembalian = ?,
            status_waktu = ?
        WHERE id = ?
    ");
    
    $condition_capitalized = ucfirst($condition);
    $update_item_stmt->bind_param("sssssi", $condition_capitalized, $notes, $optimized_condition_photo, $optimized_placement_photo, $status_waktu, $item_id);
    
    if (!$update_item_stmt->execute()) {
        throw new Exception('Gagal mengupdate item: ' . $update_item_stmt->error);
    }
    $update_item_stmt->close();
    
    // Update stock availability based on condition
    if ($condition == 'baik') {
        // Return to available stock - update status to 'Tersedia'
        $update_stock_stmt = $conn->prepare("
            UPDATE color_stock_items_semarang 
            SET status = 'Tersedia' 
            WHERE id = ?
        ");
        $update_stock_stmt->bind_param("i", $item['stock_id']);
        
        if (!$update_stock_stmt->execute()) {
            throw new Exception('Gagal mengupdate status stock: ' . $update_stock_stmt->error);
        }
        $update_stock_stmt->close();
        
        // Update available quantity in color_panel_components_semarang
        $update_availability_stmt = $conn->prepare("
            UPDATE color_panel_components_semarang 
            SET available_quantity = available_quantity + 1 
            WHERE color_id = ? AND component_id = ?
        ");
        $update_availability_stmt->bind_param("ii", $item['color_id'], $item['component_id']);
        
        if (!$update_availability_stmt->execute()) {
            throw new Exception('Gagal mengupdate ketersediaan: ' . $update_availability_stmt->error);
        }
        $update_availability_stmt->close();
        
    } else {
        // For 'rusak' or 'hilang', set appropriate status and don't return to available quantity
        $new_status = ($condition == 'rusak') ? 'Rusak' : 'Hilang';
        
        $update_stock_stmt = $conn->prepare("
            UPDATE color_stock_items_semarang 
            SET status = ? 
            WHERE id = ?
        ");
        $update_stock_stmt->bind_param("si", $new_status, $item['stock_id']);
        
        if (!$update_stock_stmt->execute()) {
            throw new Exception('Gagal mengupdate status stock: ' . $update_stock_stmt->error);
        }
        $update_stock_stmt->close();
    }
    
    // Check if all items in transaction are returned
    $check_completion_stmt = $conn->prepare("
        SELECT COUNT(*) as total_items,
               SUM(dikembalikan) as returned_items
        FROM transaction_items_semarang 
        WHERE transaction_id = ?
    ");
    $check_completion_stmt->bind_param("i", $item['transaction_id']);
    $check_completion_stmt->execute();
    $completion_result = $check_completion_stmt->get_result();
    $completion_data = $completion_result->fetch_assoc();
    $check_completion_stmt->close();
    
    // If all items are returned, update transaction status
    $transaction_completed = false;
    if ($completion_data['total_items'] == $completion_data['returned_items']) {
        $update_transaction_stmt = $conn->prepare("
            UPDATE stock_transactions_semarang 
            SET status_peminjaman = 'Dikembalikan' 
            WHERE id = ?
        ");
        $update_transaction_stmt->bind_param("i", $item['transaction_id']);
        
        if (!$update_transaction_stmt->execute()) {
            throw new Exception('Gagal mengupdate status transaksi: ' . $update_transaction_stmt->error);
        }
        $update_transaction_stmt->close();
        $transaction_completed = true;
    }
    
    // Create detailed audit log
    $condition_text = ucfirst($condition);
    $notes_text = !empty($notes) ? ' dengan catatan: ' . $notes : '';
    $photo_text = ' dengan bukti foto';
    
    $audit_details = "Borrower returned item {$item['kode_barang']} in condition: {$condition_text} with notes: {$notes}";
    
    create_audit_log(
        $conn, 
        'Return Item', 
        $_SESSION['user_id'], 
        'borrower', 
        $audit_details
    );
    
    // Commit transaction
    $conn->commit();
    
    // Prepare response data
    $response_data = [
        'success' => true, 
        'message' => 'Item berhasil dikembalikan',
        'status_waktu' => $status_waktu,
        'condition' => $condition_capitalized,
        'item_details' => [
            'kode_barang' => $item['kode_barang'],
            'code_color' => $item['code_color'],
            'component_name' => $item['component_name'],
            'nama_buyer' => $item['nama_buyer'],
            'reservation_number' => $item['reservation_number'],
            'rack_no' => $item['rack_no'],
            'lokasi' => $item['lokasi']
        ],
        'return_info' => [
            'return_time' => date('Y-m-d H:i:s'),
            'is_on_time' => $status_waktu === 'tepat',
            'transaction_completed' => $transaction_completed,
            'returned_items' => $completion_data['returned_items'],
            'total_items' => $completion_data['total_items']
        ],
        'photos' => [
            'condition_photo_size' => strlen($optimized_condition_photo),
            'placement_photo_size' => strlen($optimized_placement_photo),
            'optimization_applied' => true
        ]
    ];
    
    echo json_encode($response_data);

} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    
    // Log detailed error
    error_log("Return process error for user " . $_SESSION['user_id'] . ", item " . $item_id . ": " . $e->getMessage());
    
    echo json_encode([
        'success' => false, 
        'message' => 'Terjadi kesalahan: ' . $e->getMessage(),
        'error_code' => 'RETURN_PROCESS_ERROR',
        'timestamp' => date('Y-m-d H:i:s')
    ]);
}

// Close connection
$conn->close();
?>