<?php
// Tentukan path folder penyimpanan
$folderPath = "uploads/";

// --- LOGIKA PEMBUATAN FOLDER OTOMATIS ---
if (!is_dir($folderPath)) {
    $created = mkdir($folderPath, 0777, true);
    
    if (!$created) {
        die("Error: Gagal membuat folder penyimpanan ('$folderPath'). Mohon periksa izin akses PHP.");
    }
}
// --- AKHIR LOGIKA PEMBUATAN FOLDER OTOMATIS ---

// Pastikan data POST dikirim
if (!isset($_POST['image']) || !isset($_POST['nama']) || !isset($_POST['ratio'])) {
    die("Error: Data tidak lengkap.");
}

$img = $_POST['image'];
$nama_input = $_POST['nama'];
$ratio = $_POST['ratio'];

// --- 1. Memproses Nama dan Pemformatan Spasi menjadi Underscore ---
$nama_bersih = trim($nama_input);
$nama_file_dasar = str_replace(' ', '_', $nama_bersih);
$fileName = $nama_file_dasar . '_' . time() . '.jpeg';

// --- 2. Mengubah data Base64 menjadi file Gambar ---
$image_parts = explode(";base64,", $img);
if (count($image_parts) < 2) {
    die("Error: Format data gambar tidak valid.");
}
$image_base64 = base64_decode($image_parts[1]);

// --- 3. Manipulasi Gambar (Resize & Crop 3x4) ---
$target_width = 120;
$target_height = 160;

if (!extension_loaded('gd')) {
    die("Error: Ekstensi GD PHP tidak aktif. Fungsi manipulasi gambar tidak dapat dijalankan.");
}

$source_image = imagecreatefromstring($image_base64);

if (!$source_image) {
    die("Error: Gagal memproses gambar sumber (mungkin data Base64 rusak).");
}

$original_width = imagesx($source_image);
$original_height = imagesy($source_image);

// Calculation for 3x4 Cropping and Resizing
$ratio_target = $target_width / $target_height;
$ratio_original = $original_width / $original_height;

$crop_width = $original_width;
$crop_height = $original_height;
$crop_x = 0;
$crop_y = 0;

if ($ratio_original > $ratio_target) {
    $crop_width = $original_height * $ratio_target;
    $crop_x = ($original_width - $crop_width) / 2;
} else if ($ratio_original < $ratio_target) {
    $crop_height = $original_width / $ratio_target;
    $crop_y = ($original_height - $crop_height) / 2;
}

$target_image = imagecreatetruecolor($target_width, $target_height);

imagecopyresampled(
    $target_image,
    $source_image,
    0, 0,
    (int)$crop_x, (int)$crop_y,
    $target_width, $target_height,
    (int)$crop_width, (int)$crop_height
);

// --- 4. Menyimpan File ---
$filePath = $folderPath . $fileName;
$quality = 95;

$success = imagejpeg($target_image, $filePath, $quality);

// --- 5. Membersihkan Memori GD ---
imagedestroy($source_image);
imagedestroy($target_image);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Status Penyimpanan Foto</title>
    <style>
        :root {
            --primary-color: #007bff;
            --success-color: #28a745;
            --danger-color: #dc3545;
            --background-color: #f8f9fa;
            --card-background: #ffffff;
            --border-radius: 16px;
            --shadow-light: 0 2px 10px rgba(0, 0, 0, 0.08);
            --shadow-medium: 0 8px 30px rgba(0, 0, 0, 0.12);
            --text-primary: #2c3e50;
            --text-secondary: #6c757d;
            --text-light: #95a5a6;
            --border-color: #e9ecef;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            margin: 0;
            padding: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            line-height: 1.6;
        }

        .result-card {
            background: var(--card-background);
            padding: 3rem;
            border-radius: var(--border-radius);
            box-shadow: var(--shadow-medium);
            max-width: 520px;
            width: 100%;
            text-align: center;
            transition: all 0.3s ease;
            border: 1px solid var(--border-color);
        }

        .result-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 40px rgba(0, 0, 0, 0.15);
        }

        /* Ikon Status */
        .icon {
            font-size: 4.5rem;
            margin-bottom: 1.5rem;
            display: block;
            line-height: 1;
            filter: drop-shadow(0 4px 8px rgba(0,0,0,0.1));
        }

        /* Status Sukses */
        .status-success .icon {
            color: var(--success-color);
            animation: bounceIn 0.6s ease;
        }

        .status-success h1 {
            color: var(--success-color);
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }

        /* Status Gagal */
        .status-failure .icon {
            color: var(--danger-color);
            animation: shake 0.5s ease;
        }

        .status-failure h1 {
            color: var(--danger-color);
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        /* Deskripsi */
        .description {
            color: var(--text-secondary);
            margin-bottom: 2rem;
            font-size: 1.1rem;
            line-height: 1.6;
        }

        /* Detail Box */
        .detail-box {
            background: #f8f9fa;
            padding: 1.5rem;
            border-radius: 12px;
            margin: 2rem 0;
            text-align: left;
            border: 1px solid var(--border-color);
        }

        .detail-item {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 0.75rem;
            padding-bottom: 0.75rem;
            border-bottom: 1px solid var(--border-color);
        }

        .detail-item:last-child {
            margin-bottom: 0;
            padding-bottom: 0;
            border-bottom: none;
        }

        .detail-label {
            font-weight: 600;
            color: var(--text-primary);
            min-width: 120px;
            font-size: 0.95rem;
        }

        .detail-value {
            color: var(--text-secondary);
            text-align: right;
            flex: 1;
            font-family: 'Courier New', monospace;
            font-size: 0.9rem;
            word-break: break-all;
            padding-left: 1rem;
        }

        /* Foto Preview */
        .photo-preview {
            margin: 2rem 0;
            padding: 1rem;
            background: #f8f9fa;
            border-radius: 12px;
            border: 1px solid var(--border-color);
        }

        .photo-preview img {
            max-width: 180px;
            height: auto;
            border-radius: 8px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            border: 3px solid white;
            transition: transform 0.3s ease;
        }

        .photo-preview img:hover {
            transform: scale(1.05);
        }

        .photo-label {
            display: block;
            color: var(--text-secondary);
            font-size: 0.9rem;
            margin-top: 0.5rem;
            font-weight: 500;
        }

        /* Tombol */
        .back-link {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-top: 1.5rem;
            padding: 0.875rem 2rem;
            background: var(--primary-color);
            color: white;
            text-decoration: none;
            border-radius: 8px;
            transition: all 0.3s ease;
            font-weight: 600;
            font-size: 1rem;
            box-shadow: 0 4px 12px rgba(0, 123, 255, 0.3);
            border: none;
            cursor: pointer;
            gap: 0.5rem;
        }

        .back-link:hover {
            background: #0056b3;
            box-shadow: 0 6px 20px rgba(0, 123, 255, 0.4);
            transform: translateY(-2px);
        }

        /* List untuk error */
        .error-list {
            text-align: left;
            margin: 1rem 0;
        }

        .error-list li {
            margin-bottom: 0.5rem;
            color: var(--text-secondary);
            padding-left: 1rem;
            position: relative;
        }

        .error-list li:before {
            content: "•";
            color: var(--danger-color);
            font-weight: bold;
            position: absolute;
            left: 0;
        }

        /* Animations */
        @keyframes bounceIn {
            0% { transform: scale(0.3); opacity: 0; }
            50% { transform: scale(1.05); }
            70% { transform: scale(0.9); }
            100% { transform: scale(1); opacity: 1; }
        }

        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
            20%, 40%, 60%, 80% { transform: translateX(5px); }
        }

        /* Responsive */
        @media (max-width: 576px) {
            body {
                padding: 15px;
            }
            
            .result-card {
                padding: 2rem 1.5rem;
            }
            
            .icon {
                font-size: 3.5rem;
            }
            
            .status-success h1,
            .status-failure h1 {
                font-size: 1.75rem;
            }
            
            .detail-item {
                flex-direction: column;
                align-items: flex-start;
            }
            
            .detail-value {
                text-align: left;
                padding-left: 0;
                margin-top: 0.25rem;
            }
            
            .photo-preview img {
                max-width: 140px;
            }
        }
    </style>
</head>
<body>

    <?php if ($success): ?>
        <div class="result-card status-success">
            <span class="icon">✅</span>
            <h1>Penyimpanan Berhasil!</h1>
            <p class="description">Foto Pas Foto 3x4 telah berhasil diproses dan disimpan ke server.</p>
            
            <div class="detail-box">
                <div class="detail-item">
                    <span class="detail-label">Nama File:</span>
                    <span class="detail-value"><?php echo htmlspecialchars($fileName); ?></span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">Lokasi Folder:</span>
                    <span class="detail-value"><?php echo htmlspecialchars($folderPath); ?></span>
                </div>
            </div>
            
            <div class="photo-preview">
                <img src='<?php echo htmlspecialchars($filePath); ?>' alt='Foto Tersimpan'>
                <span class="photo-label">Preview Foto</span>
            </div>

            <a href='index.php' class='back-link'>
                <span>📷</span>
                Ambil Foto Lagi
            </a>
        </div>
    <?php else: ?>
        <div class="result-card status-failure">
            <span class="icon">❌</span>
            <h1>Penyimpanan Gagal!</h1>
            <p class="description">Terjadi kesalahan saat menyimpan file. Silakan periksa detail di bawah:</p>
            
            <div class="detail-box">
                <div class="detail-item">
                    <span class="detail-label">Penyebab Umum:</span>
                </div>
                <ul class="error-list">
                    <li>Izin tulis pada folder <code>uploads/</code> ditolak</li>
                    <li>Ekstensi PHP GD tidak aktif</li>
                    <li>Space disk tidak mencukupi</li>
                </ul>
                
                <div class="detail-item" style="margin-top: 1rem; padding-top: 1rem; border-top: 1px solid var(--border-color);">
                    <span class="detail-label">Solusi:</span>
                    <span class="detail-value">Periksa izin folder dan pastikan ekstensi GD aktif</span>
                </div>
            </div>

            <a href='index.php' class='back-link'>
                <span>↶</span>
                Kembali ke Kamera
            </a>
        </div>
    <?php endif; ?>

</body>
</html>