<?php
// PHP logic for calculating storage
$numDrives = isset($_POST['numDrives']) ? intval($_POST['numDrives']) : 4;
$driveSize = isset($_POST['driveSize']) ? intval($_POST['driveSize']) : 12;
$raidType = isset($_POST['raidType']) ? $_POST['raidType'] : 'RAID5';

$usableStorageTB = 0;
$faultTolerance = 0;
$driveStates = [];

$totalRawCapacity = $numDrives * $driveSize;
// Assuming 10GB (0.01TB) per drive for system reserved space
$systemReservedTB = $numDrives * 0.01;
$protectionTB = 0;
$unusedTB = 0;

// Function to display error messages (these errors are handled client-side now for live updates)
function displayError($message) {
    global $usableStorageTB, $faultTolerance, $systemReservedTB, $protectionTB, $unusedTB, $driveStates, $totalRawCapacity;
    $usableStorageTB = 0;
    $faultTolerance = 'N/A';
    $systemReservedTB = 0;
    $protectionTB = 0;
    $unusedTB = 0;
    $driveStates = [];
    $totalRawCapacity = 0;
}

// Input validation and calculation
if ($numDrives < 1 || $driveSize < 1) {
    displayError('Invalid Input');
} else {
    switch ($raidType) {
        case 'RAID0':
            $usableStorageTB = $totalRawCapacity - $systemReservedTB;
            $faultTolerance = 0;
            for ($i = 0; $i < $numDrives; $i++) {
                $driveStates[] = 'usable';
            }
            break;
        case 'RAID1':
            if ($numDrives < 2) {
                displayError('Min 2 Drives for RAID 1');
                break;
            }
            $usableStorageTB = $driveSize - $systemReservedTB;
            $protectionTB = ($numDrives - 1) * $driveSize;
            $faultTolerance = $numDrives - 1;
            $driveStates[] = 'usable';
            for ($i = 1; $i < $numDrives; $i++) {
                $driveStates[] = 'mirror';
            }
            break;
        case 'RAID5':
            if ($numDrives < 3) {
                displayError('Min 3 Drives for RAID 5');
                break;
            }
            $usableStorageTB = ($numDrives - 1) * $driveSize - $systemReservedTB;
            $protectionTB = $driveSize;
            $faultTolerance = 1;
            for ($i = 0; $i < $numDrives - 1; $i++) {
                $driveStates[] = 'usable';
            }
            $driveStates[] = 'parity';
            break;
        case 'RAID6':
            if ($numDrives < 4) {
                displayError('Min 4 Drives for RAID 6');
                break;
            }
            $usableStorageTB = ($numDrives - 2) * $driveSize - $systemReservedTB;
            $protectionTB = 2 * $driveSize;
            $faultTolerance = 2;
            for ($i = 0; $i < $numDrives - 2; $i++) {
                $driveStates[] = 'usable';
            }
            $driveStates[] = 'parity';
            $driveStates[] = 'parity';
            break;
        case 'RAID10':
            if ($numDrives < 4 || $numDrives % 2 !== 0) {
                displayError('Min 4 Even Drives for RAID 10');
                break;
            }
            $usableStorageTB = ($numDrives / 2) * $driveSize - $systemReservedTB;
            $protectionTB = ($numDrives / 2) * $driveSize;
            $faultTolerance = $numDrives / 2;
            for ($i = 0; $i < $numDrives / 2; $i++) {
                $driveStates[] = 'usable';
                $driveStates[] = 'mirror';
            }
            break;
        case 'SHR':
            if ($numDrives < 2) {
                $usableStorageTB = $driveSize - $systemReservedTB;
                $faultTolerance = 0;
                $driveStates[] = 'usable';
            } else {
                $usableStorageTB = ($numDrives - 1) * $driveSize - $systemReservedTB;
                $protectionTB = $driveSize;
                $faultTolerance = 1;
                for ($i = 0; $i < $numDrives - 1; $i++) {
                    $driveStates[] = 'usable';
                }
                $driveStates[] = 'parity';
            }
            break;
        case 'UnRAID':
            if ($numDrives < 1) { /* Handled by initial validation */ }
            else if ($numDrives === 1) {
                $usableStorageTB = $driveSize - $systemReservedTB;
                $faultTolerance = 0;
                $driveStates[] = 'usable';
            } else {
                $usableStorageTB = ($numDrives - 1) * $driveSize - $systemReservedTB;
                $protectionTB = $driveSize;
                $faultTolerance = 1;
                $driveStates[] = 'parity';
                for ($i = 1; $i < $numDrives; $i++) {
                    $driveStates[] = 'usable';
                }
            }
            break;
        default:
            $usableStorageTB = 0;
            $faultTolerance = 0;
            break;
    }

    $usableStorageTB = max(0, $usableStorageTB);
    $protectionTB = max(0, $protectionTB);
    $systemReservedTB = max(0, $systemReservedTB);
    $unusedTB = $totalRawCapacity - $usableStorageTB - $protectionTB - $systemReservedTB;
    $unusedTB = max(0, $unusedTB);
}

// Function to generate capacity bar HTML
function generateCapacityBar($totalRaw, $reserved, $available, $protection, $unused) {
    $segments = [
        ['label' => 'Reserved', 'value' => $reserved, 'className' => 'segment-reserved'],
        ['label' => 'Available', 'value' => $available, 'className' => 'segment-available'],
        ['label' => 'Protection', 'value' => $protection, 'className' => 'segment-protection'],
        ['label' => 'Unused', 'value' => $unused, 'className' => 'segment-unused']
    ];

    $barHtml = '';
    if ($totalRaw > 0) {
        foreach ($segments as $segment) {
            $widthPercent = ($segment['value'] / $totalRaw) * 100;
            if ($widthPercent > 0.5) {
                $barHtml .= '<div class="capacity-segment ' . $segment['className'] . '" style="width: ' . $widthPercent . '%;"></div>';
            }
        }
    }
    return $barHtml;
}

// Generate drive visualizer HTML
function generateDriveVisualizer($numDrives, $driveSize, $driveStates) {
    $visualizerHtml = '';
    for ($i = 0; $i < $numDrives; $i++) {
        $visualizerHtml .= '<div class="drive-icon drive-' . $driveStates[$i] . '"><span>' . $driveSize . 'TB</span></div>';
    }
    return $visualizerHtml;
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Podcast Storage Calculator</title>
    <!-- Tailwind CSS CDN for easy styling -->
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        /* Custom font for a clean look */
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap');
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #a78bfa 0%, #818cf8 100%); /* Vibrant gradient background */
            display: flex;
            flex-direction: column; /* Allow content to stack vertically */
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            padding: 10px; /* Reduced padding */
            box-sizing: border-box;
            overflow-x: hidden; /* Prevent horizontal scroll */
        }
        .calculator-container {
            background-color: #ffffff;
            border-radius: 12px; /* Slightly less rounded for compactness */
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2); /* Stronger shadow */
            padding: 20px; /* Reduced padding */
            width: 100%; /* Full width within its container (iframe) */
            display: flex;
            flex-direction: column;
            gap: 15px; /* Reduced gap */
            box-sizing: border-box;
            border: 2px solid #6366f1; /* Accent border */
        }
        h1 {
            color: #4338ca; /* Darker indigo for headings */
            font-size: 1.8rem; /* Smaller heading */
            margin-bottom: 15px; /* Reduced margin */
            text-shadow: 1px 1px 2px rgba(0,0,0,0.05); /* Subtle text shadow */
        }
        .input-group, .result-group {
            display: flex;
            flex-direction: column;
            gap: 8px; /* Reduced gap */
        }
        label {
            font-weight: 700; /* Bolder labels */
            color: #334155; /* Darker text for labels */
            font-size: 0.95rem; /* Smaller labels */
        }
        select, input[type="number"] {
            padding: 8px 10px; /* Reduced padding */
            border: 2px solid #a5b4fc; /* Thicker, more colorful border */
            border-radius: 8px; /* Slightly less rounded */
            font-size: 0.9rem; /* Smaller font */
            color: #334155;
            background-color: #f0f4f8; /* Light background for inputs */
            transition: border-color 0.3s ease-in-out, box-shadow 0.3s ease-in-out;
            box-shadow: inset 0 1px 3px rgba(0,0,0,0.08); /* Inner shadow for depth */
        }
        select:focus, input[type="number"]:focus {
            outline: none;
            border-color: #4f46e5; /* Stronger indigo on focus */
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.3); /* More prominent shadow on focus */
        }
        .result-box {
            background-color: #818cf8; /* Bright indigo background for results */
            padding: 12px; /* Reduced padding */
            border-radius: 8px;
            font-weight: 800; /* Extra bold */
            color: #ffffff; /* White text for contrast */
            text-align: center;
            font-size: 1.2rem; /* Smaller result text */
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15); /* Shadow for results */
            border: 1px solid #6366f1; /* Border for results */
        }
        .result-label {
            font-weight: 700;
            color: #334155;
            margin-bottom: 5px;
            font-size: 0.95rem;
        }
        .drive-visualizer {
            display: flex;
            flex-wrap: wrap; /* Allow drives to wrap to next line */
            gap: 5px; /* Small gap between drives */
            justify-content: center;
            margin-top: 10px;
        }
        .drive-icon {
            width: 40px; /* Small drive icon size */
            height: 40px;
            border-radius: 6px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            font-size: 0.65rem; /* Very small text for drive size */
            font-weight: 600;
            color: #ffffff;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            position: relative;
            overflow: hidden; /* Hide overflow for text */
        }
        .drive-icon::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-size: cover;
            background-position: center;
            opacity: 0.2; /* Subtle background pattern */
            z-index: 0;
        }
        .drive-icon span {
            position: relative;
            z-index: 1;
            text-align: center;
            line-height: 1;
        }

        /* Drive icon colors based on type */
        .drive-usable {
            background-color: #10b981; /* Green for usable */
            border: 1px solid #059669;
        }
        .drive-usable::before {
            background-image: url('data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="%23ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"%3E%3Cpath d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z"/%3E%3Cpolyline points="12 6 12 12 16 14"/%3E%3C/svg%3E'); /* Clock icon for usable */
        }
        .drive-parity {
            background-color: #f59e0b; /* Amber for parity */
            border: 1px solid #d97706;
        }
        .drive-parity::before {
            background-image: url('data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="%23ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"%3E%3Cpath d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z"/%3E%3Cpath d="M12 8v4l3 3"/%3E%3C/svg%3E'); /* Gear icon for parity */
        }
        .drive-mirror {
            background-color: #6366f1; /* Indigo for mirror */
            border: 1px solid #4f46e5;
        }
        .drive-mirror::before {
            background-image: url('data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="%23ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"%3E%3Cpath d="M16 17l5-5-5-5M8 17l-5-5 5-5"/%3E%3C/svg%3E'); /* Mirror icon */
        }
        .drive-unused {
            background-color: #94a3b8; /* Gray for unused/wasted */
            border: 1px solid #64748b;
        }
        .drive-unused::before {
            background-image: url('data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="%23ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"%3E%3Ccircle cx="12" cy="12" r="10"/%3E%3Cline x1="15" y1="9" x2="9" y2="15"/%3E%3Cline x1="9" y1="9" x2="15" y2="15"/%3E%3C/svg%3E'); /* X icon for unused */
        }

        /* New Capacity Bar Styling */
        .capacity-bar-container {
            width: 100%;
            height: 25px; /* Height of the bar */
            background-color: #e2e8f0; /* Light background for the bar */
            border-radius: 5px;
            display: flex;
            overflow: hidden; /* Ensure segments stay within bounds */
            margin-top: 10px;
            box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);
        }
        .capacity-segment {
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 0.7rem;
            font-weight: 600;
            white-space: nowrap; /* Prevent text wrapping */
            overflow: hidden; /* Hide overflow text */
            text-overflow: ellipsis; /* Add ellipsis for overflow */
        }
        .segment-reserved { background-color: #ef4444; /* Red */ }
        .segment-available { background-color: #16a34a; /* Dark Green */ }
        .segment-protection { background-color: #f97316; /* Orange */ }
        .segment-unused { background-color: #64748b; /* Slate Gray */ }

        .model-recommendations {
            margin-top: 20px; /* Reduced margin */
            padding: 20px; /* Reduced padding */
            background-color: #ffffff;
            border-radius: 12px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
            width: 100%; /* Full width within its container (iframe) */
            text-align: center;
            border: 2px solid #6366f1; /* Accent border */
        }
        h2 {
            color: #4338ca;
            font-size: 1.5rem; /* Smaller heading */
            margin-bottom: 15px;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.05);
        }
        .model-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); /* Allow models to spread if space permits */
            gap: 15px; /* Reduced gap */
            margin-top: 10px;
        }
        .model-card {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 8px; /* Reduced gap */
            background: linear-gradient(180deg, #e0e7ff 0%, #c7d2fe 100%); /* Light gradient for cards */
            border-radius: 10px; /* More rounded */
            padding: 15px; /* Reduced padding */
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1); /* Soft shadow */
            transition: transform 0.3s ease-in-out, box-shadow 0.3s ease-in-out;
            border: 1px solid #a5b4fc; /* Subtle border */
        }
        .model-card:hover {
            transform: translateY(-5px); /* Less pronounced lift on hover */
            box-shadow: 0 8px 18px rgba(0, 0, 0, 0.15); /* Stronger shadow on hover */
        }
        .model-card img {
            width: 80px; /* Smaller thumbnails */
            height: 60px; /* Smaller thumbnails */
            border-radius: 6px; /* More rounded image corners */
            object-fit: cover;
            border: 2px solid #818cf8; /* Colorful border for images */
            box-shadow: 0 3px 6px rgba(0,0,0,0.1);
        }
        .model-card h3 {
            font-size: 1rem; /* Smaller font */
            font-weight: 700;
            color: #4338ca;
            margin-bottom: 3px;
        }
        .model-card p {
            font-size: 0.8rem; /* Smaller font */
            color: #475569;
            text-align: center;
            line-height: 1.3;
        }
        .model-card a {
            display: inline-block;
            background-color: #4f46e5; /* Vibrant button color */
            color: #ffffff;
            padding: 8px 15px; /* Reduced padding */
            border-radius: 6px; /* Slightly less rounded */
            font-weight: 600;
            text-decoration: none;
            font-size: 0.85rem; /* Smaller font */
            transition: background-color 0.3s ease-in-out, transform 0.2s ease-in-out;
            box-shadow: 0 3px 8px rgba(0, 0, 0, 0.15);
        }
        .model-card a:hover {
            background-color: #312e81; /* Darker on hover */
            transform: translateY(-1px);
        }

        /* Responsive adjustments for smaller iframes */
        @media (max-width: 350px) {
            .calculator-container, .model-recommendations {
                padding: 15px;
                gap: 10px;
            }
            h1 {
                font-size: 1.6rem;
            }
            h2 {
                font-size: 1.3rem;
            }
            label, .result-label {
                font-size: 0.9rem;
            }
            select, input[type="number"], .result-box {
                font-size: 0.85rem;
                padding: 6px 8px;
            }
            .drive-icon {
                width: 35px;
                height: 35px;
                font-size: 0.6rem;
            }
            .capacity-bar-container {
                height: 20px;
            }
            .capacity-segment {
                font-size: 0.6rem;
            }
            .model-card img {
                width: 70px;
                height: 50px;
            }
            .model-card h3 {
                font-size: 0.9rem;
            }
            .model-card p {
                font-size: 0.75rem;
            }
            .model-card a {
                font-size: 0.8rem;
                padding: 6px 12px;
            }
            .model-grid {
                grid-template-columns: 1fr; /* Force single column on very small widths */
            }
        }
    </style>
</head>
<body>
    <div class="calculator-container">
        <h1 class="font-bold text-center mb-4">Podcast Storage Calculator</h1>

        <form method="POST" action="">
            <div class="input-group">
                <label for="numDrives">Number of Drives:</label>
                <input type="number" id="numDrives" name="numDrives" value="<?php echo $numDrives; ?>" min="1" max="18" onchange="this.form.submit()" onkeyup="this.form.submit()">
            </div>

            <div class="input-group">
                <label for="driveSize">Size of Each Drive (TB):</label>
                <select id="driveSize" name="driveSize" onchange="this.form.submit()">
                    <?php
                    $driveSizes = [1, 2, 4, 8, 12, 16, 20, 22];
                    foreach ($driveSizes as $size) {
                        $selected = ($driveSize == $size) ? 'selected' : '';
                        echo "<option value=\"{$size}\" {$selected}>{$size} TB</option>";
                    }
                    ?>
                </select>
            </div>

            <div class="input-group">
                <label for="raidType">RAID Type:</label>
                <select id="raidType" name="raidType" onchange="this.form.submit()">
                    <?php
                    $raidTypes = [
                        'RAID0' => 'RAID 0 (Striping)',
                        'RAID1' => 'RAID 1 (Mirroring)',
                        'RAID5' => 'RAID 5 (Distributed Parity)',
                        'RAID6' => 'RAID 6 (Double Parity)',
                        'RAID10' => 'RAID 10 (Striping of Mirrors)',
                        'SHR' => 'Synology Hybrid RAID (SHR)',
                        'UnRAID' => 'UnRAID'
                    ];
                    foreach ($raidTypes as $value => $label) {
                        $selected = ($raidType == $value) ? 'selected' : '';
                        echo "<option value=\"{$value}\" {$selected}>{$label}</option>";
                    }
                    ?>
                </select>
            </div>
        </form>

        <div class="result-group">
            <div class="result-label">Usable Storage:</div>
            <div id="usableStorage" class="result-box"><?php echo number_format($usableStorageTB, 2); ?> TB</div>
            <div id="driveVisualizer" class="drive-visualizer">
                <?php echo generateDriveVisualizer($numDrives, $driveSize, $driveStates); ?>
            </div>
        </div>

        <!-- New Capacity Breakdown Section -->
        <div class="result-group">
            <div class="result-label">Capacity Breakdown:</div>
            <div id="capacityBarContainer" class="capacity-bar-container">
                <?php echo generateCapacityBar($totalRawCapacity, $systemReservedTB, $usableStorageTB, $protectionTB, $unusedTB); ?>
            </div>
            <div class="flex justify-between text-xs mt-2 text-gray-600">
                <span id="reservedText">Reserved: <?php echo number_format($systemReservedTB, 1); ?>TB</span>
                <span id="availableText">Available: <?php echo number_format($usableStorageTB, 1); ?>TB</span>
                <span id="protectionText">Protection: <?php echo number_format($protectionTB, 1); ?>TB</span>
                <span id="unusedText">Unused: <?php echo number_format($unusedTB, 1); ?>TB</span>
            </div>
        </div>
        <!-- End New Capacity Breakdown Section -->

        <div class="result-group">
            <div class="result-label">Fault Tolerance:</div>
            <div id="faultTolerance" class="result-box"><?php echo $faultTolerance; ?> Drives</div>
        </div>
    </div>

    <div class="model-recommendations">
        <h2 class="font-bold text-gray-800 mb-4">Recommended NAS Models for Podcasters</h2>
        <div class="model-grid">
            <!-- Model 1 -->
            <div class="model-card">
                <img src="https://podcastpontifications.com/raid-calculator/synology.jpg" alt="Synology 1522+">
                <h3>Synology 1522+</h3>
                <p>Compact 5-bay NAS, great for beginners and expandable.</p>
                <a href="https://amzn.to/3IiApRE" target="_blank" rel="noopener noreferrer">Check Price</a>
            </div>
            <!-- Model 2 -->
            <div class="model-card">
                <img src="https://podcastpontifications.com/raid-calculator/qnap.jpg" alt="QNAP TS-464">
                <h3>QNAP TS-464</h3>
                <p>4-bay NAS with 2.5GbE, ideal for growing podcasts.</p>
                <a href="https://amzn.to/4lhVYjS" target="_blank" rel="noopener noreferrer">Check Price</a>
            </div>
            <!-- Model 3 -->
            <div class="model-card">
                <img src="https://podcastpontifications.com/raid-calculator/terramaster.jpg" alt="TerraMaster F4-423">
                <h3>TerraMaster F4-423</h3>
                <p>Cost-effective 4-bay with dual 2.5GbE, good value.</p>
                <a href="https://amzn.to/4eXBj2x" target="_blank" rel="noopener noreferrer">Check Price</a>
            </div>
            <!-- Model 4 -->
            <div class="model-card">
                <img src="https://podcastpontifications.com/raid-calculator/asustor.jpg" alt="Asustor AS5404T">
                <h3>Asustor AS5404T</h3>
                <p>Powerful 4-bay for advanced users, great performance.</p>
                <a href="https://amzn.to/4lAUqkWT" target="_blank" rel="noopener noreferrer">Check Price</a>
            </div>
        </div>
    </div>

    <script>
        // This script will send the usable storage data to the parent window.
        // It runs after the PHP has rendered the page.
        window.onload = function() {
            const usableStorageElement = document.getElementById('usableStorage');
            if (usableStorageElement) {
                const usableStorageValue = usableStorageElement.textContent; // e.g., "36.00 TB"
                // Parse the number from the string
                const usableStorageNum = parseFloat(usableStorageValue.replace(' TB', ''));

                // Send a message to the parent window
                // Replace 'YOUR_PARENT_ORIGIN' with the actual origin (protocol + hostname + port)
                // of the page embedding this iframe. For example, 'https://yourwebsite.com'
                // Using '*' is less secure but works for any origin.
                window.parent.postMessage({
                    source: 'podcastStorageCalculator',
                    usableStorage: usableStorageNum
                }, '*'); // Consider replacing '*' with a specific origin for security
            }
        };
    </script>
</body>
</html>
