<?php
require_once 'config/db.php';
function portfolio_add_redirect($url) { header("Location: $url"); exit; }

// Fetch all categories
$cat_stmt = $pdo->query("SELECT id, name FROM portfolio_categories WHERE status = 'active' ORDER BY name ASC");
$categories = $cat_stmt->fetchAll();

// Fetch all subcategories
$sub_stmt = $pdo->query("SELECT id, category_id, name FROM portfolio_subcategories WHERE status = 'active' ORDER BY name ASC");
$subcategories = $sub_stmt->fetchAll();

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
    $title = trim($_POST['title']);
    
    // Custom Slug or Auto-generated
    if (!empty($_POST['custom_slug'])) {
        $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $_POST['custom_slug'])));
    } else {
        $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $title))) . '-' . time();
    }
    
    $category_id = (int)$_POST['category_id'];
    $subcategory_id = !empty($_POST['subcategory_id']) ? (int)$_POST['subcategory_id'] : null;
    $client_name = trim($_POST['client_name']);
    $completion_date = !empty($_POST['completion_date']) ? $_POST['completion_date'] : null;
    $status = $_POST['status'];
    $description = trim($_POST['description']);
    $quote_text = trim($_POST['quote_text'] ?? '');
    $meta_title = trim($_POST['meta_title'] ?? '');
    $meta_description = trim($_POST['meta_description'] ?? '');
    $meta_keywords = trim($_POST['meta_keywords'] ?? '');
    
    // Main Cover Image Upload Logic
    $image_path = "";
    $allowed = ['jpg', 'jpeg', 'png', 'webp'];
    if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
        $filename = $_FILES['image']['name'];
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        
        if (in_array($ext, $allowed)) {
            $new_filename = uniqid('portfolio_') . '.' . $ext;
            $destination = "../uploads/portfolio/" . $new_filename;
            
            if (move_uploaded_file($_FILES['image']['tmp_name'], $destination)) {
                $image_path = "uploads/portfolio/" . $new_filename;
            } else {
                $error = "Failed to move uploaded cover image.";
            }
        } else {
            $error = "Invalid file type. Only JPG, PNG, and WEBP are allowed for the cover image.";
        }
    } else {
        $error = "Cover Image is required.";
    }

    // Planning Image Upload Logic (Optional)
    $image_planning = null;
    if (!isset($error) && isset($_FILES['image_planning']) && $_FILES['image_planning']['error'] == 0) {
        $filename = $_FILES['image_planning']['name'];
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        if (in_array($ext, $allowed)) {
            $new_filename = uniqid('planning_') . '.' . $ext;
            $destination = "../uploads/portfolio/" . $new_filename;
            if (move_uploaded_file($_FILES['image_planning']['tmp_name'], $destination)) {
                $image_planning = "uploads/portfolio/" . $new_filename;
            }
        }
    }

    // Execution Image Upload Logic (Optional)
    $image_execution = null;
    if (!isset($error) && isset($_FILES['image_execution']) && $_FILES['image_execution']['error'] == 0) {
        $filename = $_FILES['image_execution']['name'];
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        if (in_array($ext, $allowed)) {
            $new_filename = uniqid('execution_') . '.' . $ext;
            $destination = "../uploads/portfolio/" . $new_filename;
            if (move_uploaded_file($_FILES['image_execution']['tmp_name'], $destination)) {
                $image_execution = "uploads/portfolio/" . $new_filename;
            }
        }
    }

    if (!isset($error)) {
        try {
            $stmt = $pdo->prepare("INSERT INTO portfolio_items (category_id, subcategory_id, title, slug, description, quote_text, client_name, completion_date, image_path, image_planning, image_execution, status, meta_title, meta_description, meta_keywords) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$category_id, $subcategory_id, $title, $slug, $description, $quote_text, $client_name, $completion_date, $image_path, $image_planning, $image_execution, $status, $meta_title, $meta_description, $meta_keywords]);
            $_SESSION['success_msg'] = "Portfolio item added successfully.";
            portfolio_add_redirect('portfolio_items.php');
        } catch (PDOException $e) {
            $error = "Database Error: " . $e->getMessage();
        }
    }
}

require_once 'includes/header.php';
?>

<div class="dashboard-content">
    <div class="welcome-banner" style="margin-bottom: 20px; padding: 20px;">
        <h2><i class="fa-solid fa-plus-circle"></i> Add Portfolio Item</h2>
        <p>Publish a new completed project to your portfolio.</p>
    </div>

    <?php if (isset($error)): ?>
        <div class="badge badge-pending" style="display:block; padding:15px; margin-bottom: 20px; background-color: #fee2e2; color: #ef4444; font-size:1rem;"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <div class="recent-activity">
        <form action="portfolio_add.php" method="POST" enctype="multipart/form-data">
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">
                <!-- Title -->
                <div>
                    <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Project Title *</label>
                    <input type="text" name="title" required style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px;" placeholder="e.g. Modern Residential Villa">
                </div>
                <!-- Status -->
                <div>
                    <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Status</label>
                    <select name="status" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px;">
                        <option value="published">Published</option>
                        <option value="draft">Draft</option>
                    </select>
                </div>
            </div>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">
                <!-- Category -->
                <div>
                    <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Category *</label>
                    <select name="category_id" id="category_select" required style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px;">
                        <option value="">-- Select Category --</option>
                        <?php foreach($categories as $cat): ?>
                            <option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <!-- Subcategory -->
                <div>
                    <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Subcategory (Optional)</label>
                    <select name="subcategory_id" id="subcategory_select" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px;">
                        <option value="">-- Select Subcategory --</option>
                        <!-- Populated via JS -->
                    </select>
                </div>
            </div>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">
                <!-- Client Name -->
                <div>
                    <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Client Name (Optional)</label>
                    <input type="text" name="client_name" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px;" placeholder="e.g. Mr. Sharma">
                </div>
                <!-- Completion Date -->
                <div>
                    <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Completion Date (Optional)</label>
                    <input type="date" name="completion_date" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px;">
                </div>
            </div>

            <!-- Custom Slug -->
            <div style="margin-bottom: 20px;">
                <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Custom URL Slug (Optional)</label>
                <input type="text" name="custom_slug" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; background:#f8fafc;" placeholder="e.g. custom-project-name">
                <small style="color: #64748b; margin-top:5px; display:block;">Leave empty to auto-generate based on Title.</small>
            </div>

            <hr style="border:0; border-top:1px dashed #e2e8f0; margin:30px 0;">
            <h3 style="margin-bottom:20px; color:var(--heading); font-family:var(--font-serif);">Media Uploads</h3>

            <!-- Image Uploads Row -->
            <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; margin-bottom: 30px;">
                <div>
                    <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Project Cover Image *</label>
                    <input type="file" name="image" accept="image/*" required style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; background:#fff;">
                </div>
                <div>
                    <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Production/Planning Image (Optional)</label>
                    <input type="file" name="image_planning" accept="image/*" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; background:#fff;">
                </div>
                <div>
                    <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Execution Image (Optional)</label>
                    <input type="file" name="image_execution" accept="image/*" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; background:#fff;">
                </div>
            </div>

            <hr style="border:0; border-top:1px dashed #e2e8f0; margin:30px 0;">
            <h3 style="margin-bottom:20px; color:var(--heading); font-family:var(--font-serif);">Project Details</h3>

            <!-- Description -->
            <div style="margin-bottom: 25px;">
                <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Project Description</label>
                <textarea name="description" rows="5" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; font-family:inherit; resize:vertical;"></textarea>
            </div>

            <!-- Blockquote/Quotes -->
            <div style="margin-bottom: 25px;">
                <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Client Quote / Highlight Text</label>
                <textarea name="quote_text" rows="3" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; font-family:inherit; resize:vertical; background:#f8fafc;" placeholder='e.g. "We were incredibly impressed by MK Construction&apos;s..."'></textarea>
            </div>

            <hr style="border:0; border-top:1px dashed #e2e8f0; margin:30px 0;">
            <h3 style="margin-bottom:20px; color:var(--heading); font-family:var(--font-serif);">SEO Settings</h3>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">
                <div>
                    <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Meta Title (Optional)</label>
                    <input type="text" name="meta_title" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px;" placeholder="Optional SEO Title override">
                </div>
                <div>
                    <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Meta Keywords (Optional)</label>
                    <input type="text" name="meta_keywords" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px;" placeholder="e.g. construction, residential, krishnagiri">
                </div>
            </div>
            <div style="margin-bottom: 30px;">
                <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Meta Description (Optional)</label>
                <textarea name="meta_description" rows="2" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; font-family:inherit; resize:vertical;" placeholder="A brief summary for search engines..."></textarea>
            </div>

            <div style="display: flex; gap: 15px;">
                <button type="submit" name="submit" class="logout-btn" style="background:var(--primary); border:none; padding:12px 25px; cursor:pointer; font-weight:600;">Publish Portfolio Item</button>
                <a href="portfolio_items.php" class="logout-btn" style="background:#e2e8f0; color:var(--text); text-decoration:none; padding:12px 25px; font-weight:600;">Cancel</a>
            </div>
        </form>
    </div>
</div>

<script>
    // Subcategory Filtering Logic
    const allSubcategories = <?= json_encode($subcategories) ?>;
    const categorySelect = document.getElementById('category_select');
    const subcategorySelect = document.getElementById('subcategory_select');

    categorySelect.addEventListener('change', function() {
        const catId = this.value;
        subcategorySelect.innerHTML = '<option value="">-- Select Subcategory --</option>'; // Reset
        
        if (catId) {
            const filtered = allSubcategories.filter(sub => sub.category_id == catId);
            filtered.forEach(sub => {
                const opt = document.createElement('option');
                opt.value = sub.id;
                opt.textContent = sub.name;
                subcategorySelect.appendChild(opt);
            });
        }
    });
</script>

<?php require_once 'includes/footer.php'; ?>
