<?php
/**
 * Admin - Edit Software Product
 */
require_once __DIR__ . '/../config.php';
require_admin_login();

$page_title = 'Edit Software Product';
$software_id = intval($_GET['id'] ?? 0);
$software = null;
$errors = [];

if ($software_id) {
    try {
        $stmt = db()->prepare("SELECT * FROM software_products WHERE id = ?");
        $stmt->execute([$software_id]);
        $software = $stmt->fetch();
    } catch (PDOException $e) {}
}

if (!$software) {
    redirect(BASE_URL . 'admin/software.php', 'error', 'Software not found');
}

// Parse existing features
$existing_features = [];
if (!empty($software['features'])) {
    $decoded = json_decode($software['features'], true);
    if (is_array($decoded)) {
        $existing_features = $decoded;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid security token';
    } else {
        $name = sanitize($_POST['name'] ?? '');
        $category = sanitize($_POST['category'] ?? 'other');
        $short_description = sanitize($_POST['short_description'] ?? '');
        $description = sanitize($_POST['description'] ?? '');
        $pricing_type = sanitize($_POST['pricing_type'] ?? 'contact');
        $price = floatval($_POST['price'] ?? 0);
        $button_link = sanitize($_POST['button_link'] ?? '');
        $button_text = sanitize($_POST['button_text'] ?? 'Explore');
        $status = isset($_POST['status']) ? 1 : 0;
        
        // Process features
        $features = [];
        if (isset($_POST['features']) && is_array($_POST['features'])) {
            foreach ($_POST['features'] as $feature) {
                $feature = trim($feature);
                if (!empty($feature)) {
                    $features[] = $feature;
                }
            }
        }
        $features_json = json_encode($features);
        
        if (empty($name)) $errors[] = 'Software name is required';
        if (empty($description)) $errors[] = 'Description is required';
        
        if (empty($errors)) {
            try {
                $stmt = db()->prepare("UPDATE software_products SET 
                    name = ?, category = ?, short_description = ?, description = ?, 
                    pricing_type = ?, price = ?, button_link = ?, button_text = ?, features = ?, status = ?, updated_at = NOW() WHERE id = ?");
                $stmt->execute([$name, $category, $short_description, $description, $pricing_type, $price, $button_link, $button_text, $features_json, $status, $software_id]);
                
                $stmt = db()->prepare("SELECT * FROM software_products WHERE id = ?");
                $stmt->execute([$software_id]);
                $software = $stmt->fetch();
                
                // Refresh features
                $existing_features = [];
                if (!empty($software['features'])) {
                    $decoded = json_decode($software['features'], true);
                    if (is_array($decoded)) {
                        $existing_features = $decoded;
                    }
                }
                
                $success = 'Software updated successfully';
            } catch (PDOException $e) {
                $errors[] = 'Failed to update software: ' . $e->getMessage();
            }
        }
    }
}

$csrf_token = generate_csrf_token();
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2 class="fw-bold mb-0">Edit Software Product</h2>
    <a href="software.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left me-2"></i>Back</a>
</div>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger"><?php foreach ($errors as $error): ?><p class="mb-0"><?php echo $error; ?></p><?php endforeach; ?></div>
<?php endif; ?>
<?php if (isset($success)): ?>
    <div class="alert alert-success"><?php echo $success; ?></div>
<?php endif; ?>

<div class="card border-0 shadow-sm">
    <div class="card-body p-4">
        <form method="POST">
            <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label">Software Name <span class="text-danger">*</span></label>
                    <input type="text" name="name" class="form-control" value="<?php echo $software['name']; ?>" required>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Category</label>
                    <select name="category" class="form-select">
                        <option value="crm" <?php echo $software['category'] == 'crm' ? 'selected' : ''; ?>>CRM</option>
                        <option value="telecalling" <?php echo $software['category'] == 'telecalling' ? 'selected' : ''; ?>>Telecalling</option>
                        <option value="erp" <?php echo $software['category'] == 'erp' ? 'selected' : ''; ?>>ERP</option>
                        <option value="marketing" <?php echo $software['category'] == 'marketing' ? 'selected' : ''; ?>>Marketing</option>
                        <option value="website" <?php echo $software['category'] == 'website' ? 'selected' : ''; ?>>Website Builder</option>
                        <option value="ai" <?php echo $software['category'] == 'ai' ? 'selected' : ''; ?>>AI Solutions</option>
                        <option value="other" <?php echo $software['category'] == 'other' ? 'selected' : ''; ?>>Other</option>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Pricing Type</label>
                    <select name="pricing_type" class="form-select">
                        <option value="free" <?php echo $software['pricing_type'] == 'free' ? 'selected' : ''; ?>>Free</option>
                        <option value="one_time" <?php echo $software['pricing_type'] == 'one_time' ? 'selected' : ''; ?>>One Time</option>
                        <option value="subscription" <?php echo $software['pricing_type'] == 'subscription' ? 'selected' : ''; ?>>Subscription</option>
                        <option value="contact" <?php echo $software['pricing_type'] == 'contact' ? 'selected' : ''; ?>>Contact for Price</option>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Price</label>
                    <input type="number" name="price" class="form-control" step="0.01" value="<?php echo $software['price'] ?? 0; ?>">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Button Text</label>
                    <input type="text" name="button_text" class="form-control" value="<?php echo $software['button_text'] ?? 'Explore'; ?>" placeholder="e.g., Explore, Try Now">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Button Link (URL)</label>
                    <input type="text" name="button_link" class="form-control" value="<?php echo $software['button_link'] ?? ''; ?>" placeholder="e.g., contact.php or https://example.com">
                    <small class="text-muted">Leave empty for default software detail page</small>
                </div>
                <div class="col-12">
                    <label class="form-label">Short Description</label>
                    <input type="text" name="short_description" class="form-control" value="<?php echo $software['short_description']; ?>">
                </div>
                <div class="col-12">
                    <label class="form-label">Full Description <span class="text-danger">*</span></label>
                    <textarea name="description" class="form-control" rows="6" required><?php echo $software['description']; ?></textarea>
                </div>
                
                <!-- Features Section -->
                <div class="col-12">
                    <label class="form-label">Features / Bullet Points</label>
                    <div id="features-container">
                        <?php 
                        $feature_count = count($existing_features);
                        if ($feature_count === 0) $feature_count = 1;
                        for ($i = 0; $i < $feature_count; $i++): 
                            $feature = $existing_features[$i] ?? '';
                        ?>
                        <div class="input-group mb-2 feature-row">
                            <span class="input-group-text"><i class="bi bi-check-circle text-success"></i></span>
                            <input type="text" name="features[]" class="form-control" value="<?php echo $feature; ?>" placeholder="Enter feature or bullet point">
                            <button type="button" class="btn btn-outline-danger remove-feature" onclick="this.closest('.feature-row').remove()">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                        <?php endfor; ?>
                    </div>
                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="addFeatureRow()">
                        <i class="bi bi-plus-circle me-1"></i>Add Feature
                    </button>
                    <small class="text-muted d-block mt-1">Add bullet points or features that will be displayed on the software product card</small>
                </div>
                
                <div class="col-12">
                    <div class="form-check">
                        <input type="checkbox" name="status" class="form-check-input" id="statusCheck" <?php echo $software['status'] ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="statusCheck">Active</label>
                    </div>
                </div>
            </div>
            <div class="mt-4">
                <button type="submit" class="btn btn-primary"><i class="bi bi-save me-2"></i>Update Software</button>
                <a href="software.php" class="btn btn-outline-secondary ms-2">Cancel</a>
            </div>
        </form>
    </div>
</div>

<script>
function addFeatureRow() {
    const container = document.getElementById('features-container');
    const row = document.createElement('div');
    row.className = 'input-group mb-2 feature-row';
    row.innerHTML = `
        <span class="input-group-text"><i class="bi bi-check-circle text-success"></i></span>
        <input type="text" name="features[]" class="form-control" placeholder="Enter feature or bullet point">
        <button type="button" class="btn btn-outline-danger remove-feature" onclick="this.closest('.feature-row').remove()">
            <i class="bi bi-trash"></i>
        </button>
    `;
    container.appendChild(row);
}
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>
