<?php
session_start();

// Database connection settings
$host = 'localhost';
$db = 'digupdog_FEED';
$user = 'digupdog_FEEDadmin';
$pass = 'Raimundinho1';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    die("Error connecting to the database: " . $e->getMessage());
}

$message = "";
$selected_ids = $_SESSION['selected_ids'] ?? [];

// If no IDs were selected, redirect back
if (empty($selected_ids)) {
    $message = "No records selected for editing.";
    header('Location: shortcut_manager.php');
    exit();
}

// Get the selected records for editing
$placeholders = implode(',', array_fill(0, count($selected_ids), '?'));
$stmt = $pdo->prepare("SELECT * FROM feed_data WHERE id IN ($placeholders)");
$stmt->execute($selected_ids);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Map the results by ID for direct access
$results_map = [];
foreach ($results as $row) {
    $results_map[$row['id']] = $row;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['mass_edit'])) {
    $updated_records = 0;

    // Retrieve the IDs actually selected by the user
    $selected_ids = isset($_POST['selected_ids']) ? explode(',', $_POST['selected_ids']) : [];

    // If no IDs were selected, do not perform any update
    if (!empty($selected_ids)) {
        // Sanitize and validate the received data
        $website_base = !empty($_POST['website_base']) ? htmlspecialchars($_POST['website_base']) : null;
        $website_feed = !empty($_POST['website_feed']) ? htmlspecialchars($_POST['website_feed']) : null;
        $main_category_id = !empty($_POST['main_category_id']) ? intval($_POST['main_category_id']) : null;
        $subcategory_id = !empty($_POST['subcategory_id']) ? intval($_POST['subcategory_id']) : null;
        $subcategory_name = !empty($_POST['subcategory_name']) ? htmlspecialchars($_POST['subcategory_name']) : null;
        $subsubcategory_id = !empty($_POST['subsubcategory_id']) ? intval($_POST['subsubcategory_id']) : null;
        $subsubcategory_name = !empty($_POST['subsubcategory_name']) ? htmlspecialchars($_POST['subsubcategory_name']) : null;
        $date_added = !empty($_POST['date_added']) ? $_POST['date_added'] : null;
        $last_updated = !empty($_POST['last_updated']) ? $_POST['last_updated'] : null;
        $is_active = isset($_POST['is_active']) ? 1 : 0;

        // Prepare the mass update query for the selected records
        $query = "UPDATE feed_data SET ";
        $params = [];

        if ($website_base) {
            $query .= "website_base = ?, ";
            $params[] = $website_base;
        }
        if ($website_feed) {
            $query .= "website_feed = ?, ";
            $params[] = $website_feed;
        }
        if ($main_category_id !== null) {
            $query .= "main_category_id = ?, ";
            $params[] = $main_category_id;
        }
        if ($subcategory_id !== null) {
            $query .= "subcategory_id = ?, ";
            $params[] = $subcategory_id;
        }
        if ($subcategory_name) {
            $query .= "subcategory_name = ?, ";
            $params[] = $subcategory_name;
        }
        if ($subsubcategory_id !== null) {
            $query .= "subsubcategory_id = ?, ";
            $params[] = $subsubcategory_id;
        }
        if ($subsubcategory_name) {
            $query .= "subsubcategory_name = ?, ";
            $params[] = $subsubcategory_name;
        }
        if ($date_added) {
            $query .= "date_added = ?, ";
            $params[] = $date_added;
        }
        if ($last_updated) {
            $query .= "last_updated = ?, ";
            $params[] = $last_updated;
        }
        $query .= "is_active = ? WHERE id IN (" . implode(',', array_fill(0, count($selected_ids), '?')) . ")";
        $params[] = $is_active;

        // Add the IDs to the end of the parameters
        $params = array_merge($params, $selected_ids);

        // Execute the update
        $stmt = $pdo->prepare($query);
        $stmt->execute($params);

        $updated_records = $stmt->rowCount();
    }

    $message = "$updated_records records successfully updated!";
    header('Location: shortcut_manager.php?message=' . urlencode($message));
    exit();
}

// Update individual records
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['data'])) {
    $updated_records = 0;
    $selected_ids = $_POST['selected_ids'] ?? [];

    foreach ($_POST['data'] as $id => $data) {
        if (in_array($id, $selected_ids)) {
            // Sanitize and validate the received data before updating
            $website_base = htmlspecialchars($data['website_base']);
            $website_feed = htmlspecialchars($data['website_feed']);
            $main_category_id = intval($data['main_category_id']);
            $subcategory_id = intval($data['subcategory_id']);
            $subcategory_name = htmlspecialchars($data['subcategory_name']);
            $subsubcategory_id = intval($data['subsubcategory_id']);
            $subsubcategory_name = htmlspecialchars($data['subsubcategory_name']);
            $date_added = !empty($data['date_added']) ? $data['date_added'] : null;
            $last_updated = !empty($data['last_updated']) ? $data['last_updated'] : null;
            $is_active = isset($data['is_active']) ? 1 : 0;

            // Check if the data has really changed before updating
            if (
                $website_base !== $results_map[$id]['website_base'] || 
                $website_feed !== $results_map[$id]['website_feed'] || 
                $main_category_id !== intval($results_map[$id]['main_category_id']) || 
                $subcategory_id !== intval($results_map[$id]['subcategory_id']) || 
                $subcategory_name !== $results_map[$id]['subcategory_name'] || 
                $subsubcategory_id !== intval($results_map[$id]['subsubcategory_id']) || 
                $subsubcategory_name !== $results_map[$id]['subsubcategory_name'] || 
                $date_added !== $results_map[$id]['date_added'] || 
                $last_updated !== $results_map[$id]['last_updated'] || 
                $is_active !== intval($results_map[$id]['is_active'])
            ) {
                // Execute the update
                $stmt = $pdo->prepare("UPDATE feed_data SET 
                    website_base = ?, 
                    website_feed = ?, 
                    main_category_id = ?, 
                    subcategory_id = ?, 
                    subcategory_name = ?, 
                    subsubcategory_id = ?, 
                    subsubcategory_name = ?, 
                    date_added = ?, 
                    last_updated = ?, 
                    is_active = ? 
                    WHERE id = ?");

                $stmt->execute([
                    $website_base,
                    $website_feed,
                    $main_category_id,
                    $subcategory_id,
                    $subcategory_name,
                    $subsubcategory_id,
                    $subsubcategory_name,
                    $date_added,
                    $last_updated,
                    $is_active,
                    $id
                ]);

                if ($stmt->rowCount()) {
                    $updated_records++;
                }
            }
        }
    }

    $message = "$updated_records records successfully updated!";
    header('Location: shortcut_manager.php?message=' . urlencode($message));
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Records - Shortcut Manager</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <style>
    /* Custom font and general layout */
    body {
        font-family: 'Poppins', sans-serif;
        background-color: #f8f9fa;
    }

    /* General container */
    .container {
        width: 95%;
        max-width: 95%;
        margin-left: auto;
        margin-right: auto;
        padding: 20px 0;
    }

    /* Modernized styles for result cards */
    .result-card {
        border: 1px solid #e0e0e0;
        border-radius: 12px;
        margin-bottom: 15px;
        padding: 20px;
        background-color: #fff;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        transition: transform 0.3s ease, box-shadow 0.3s ease;
        position: relative;
    }

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

    /* Card header */
    .result-card h4 {
        font-weight: 600;
        font-size: 20px;
        background-color: #34495e;
        padding: 12px;
        border-radius: 6px;
        color: #fff;
        margin-bottom: 20px;
        text-align: center;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    }

    /* Highlight animation on selected cards */
    .selected-card {
        border: 2px solid #007bff;
        background-color: #e9f3ff;
        animation: pulse 0.8s infinite alternate;
    }

    @keyframes pulse {
        from {
            box-shadow: 0 0 10px rgba(0, 123, 255, 0.4);
        }
        to {
            box-shadow: 0 0 20px rgba(0, 123, 255, 0.6);
        }
    }

    /* Styling inputs */
    .form-control {
        border-radius: 8px;
        padding: 12px;
        border: 1px solid #ced4da;
        transition: border-color 0.3s ease, background-color 0.3s ease;
    }

    .form-control:focus {
        border-color: #007bff;
        background-color: #f0f8ff;
        box-shadow: 0 0 8px rgba(0, 123, 255, 0.25);
    }

    /* Differentiation of correct and incorrect fields */
    .form-control.correct {
        background-color: #d4edda;
        border-color: #28a745;
    }

    .form-control.error {
        background-color: #f8d7da;
        border-color: #dc3545;
    }

    /* Button styles */
    .btn {
        padding: 12px 20px;
        border-radius: 8px;
        transition: background-color 0.3s, box-shadow 0.3s ease;
        font-size: 16px;
    }

    .btn-primary {
        background-color: #007bff;
        border-color: #007bff;
        color: white;
        display: inline-flex;
        align-items: center;
    }

    .btn-primary:hover {
        background-color: #0056b3;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
    }

    .btn-warning, .btn-danger {
        border-radius: 6px;
        padding: 10px 16px;
    }

    .btn-warning:hover, .btn-danger:hover {
        transform: scale(1.05);
    }

    .btn-warning i, .btn-danger i {
        margin-right: 5px;
    }

    /* Loading indicator */
    .loading-overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 1000;
        justify-content: center;
        align-items: center;
    }

    .loading-overlay.active {
        display: flex;
    }

    .loading-spinner {
        border: 8px solid rgba(255, 255, 255, 0.3);
        border-left-color: #fff;
        border-radius: 50%;
        width: 80px;
        height: 80px;
        animation: spin 1.2s linear infinite;
    }

    @keyframes spin {
        from {
            transform: rotate(0deg);
        }
        to {
            transform: rotate(360deg);
        }
    }

    /* Tooltips */
    [data-tooltip] {
        position: relative;
        cursor: pointer;
    }

    [data-tooltip]:hover::after {
        content: attr(data-tooltip);
        position: absolute;
        top: -30px;
        left: 50%;
        transform: translateX(-50%);
        padding: 6px 10px;
        background-color: #34495e;
        color: #fff;
        font-size: 12px;
        border-radius: 4px;
        white-space: nowrap;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
    }

    /* Custom checkbox styles */
    .form-check-input {
        width: 20px;
        height: 20px;
        margin: 0;
        cursor: pointer;
    }

    .form-check-input:checked {
        background-color: #007bff;
        border-color: #007bff;
    }

    .form-check-input:checked::before {
        content: '\2714'; /* Check symbol */
        color: #fff;
        font-size: 14px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }

    /* Responsive adjustments */
    @media (max-width: 768px) {
        .result-card .form-group {
            flex: 1 1 100%;
        }

        .btn {
            width: 100%;
            margin-top: 10px;
        }
    }
    </style>
</head>
<body>

<!-- Loading indicator -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-spinner"></div>
</div>

<div class="container mt-5">
    <h2 class="text-center">Edit Records</h2>

    <?php if ($message): ?>
        <div class="alert alert-info"><?= $message ?></div>
    <?php endif; ?>

    <!-- Mass edit form -->
    <h3 class="mt-4">Mass Edit</h3>
    <form method="post">
        <input type="hidden" name="selected_ids" id="selected_ids_hidden" value="">

        <div class="form-row">
            <div class="form-group col-md-6">
                <label for="website_base">Website Base</label>
                <input type="text" name="website_base" class="form-control" id="website_base" data-tooltip="Enter the base website URL, e.g., example.com">
            </div>
            <div class="form-group col-md-6">
                <label for="website_feed">Website Feed</label>
                <input type="text" name="website_feed" class="form-control" id="website_feed" data-tooltip="Enter the specific feed URL of the website">
            </div>
        </div>
        <div class="form-row">
            <div class="form-group col-md-4">
                <label for="main_category_id">Main Category ID</label>
                <input type="number" name="main_category_id" class="form-control" id="main_category_id" data-tooltip="Enter the main category identifier">
            </div>
            <div class="form-group col-md-4">
                <label for="subcategory_id">Subcategory ID</label>
                <input type="number" name="subcategory_id" class="form-control" id="subcategory_id" data-tooltip="Enter the subcategory identifier">
            </div>
            <div class="form-group col-md-4">
                <label for="subcategory_name">Subcategory Name</label>
                <input type="text" name="subcategory_name" class="form-control" id="subcategory_name" data-tooltip="Enter the subcategory name">
            </div>
        </div>
        <div class="form-row">
            <div class="form-group col-md-4">
                <label for="subsubcategory_id">Subsubcategory ID</label>
                <input type="number" name="subsubcategory_id" class="form-control" id="subsubcategory_id" data-tooltip="Enter the subsubcategory identifier">
            </div>
            <div class="form-group col-md-4">
                <label for="subsubcategory_name">Subsubcategory Name</label>
                <input type="text" name="subsubcategory_name" class="form-control" id="subsubcategory_name" data-tooltip="Enter the subsubcategory name">
            </div>
            <div class="form-group col-md-4">
                <label for="date_added">Date Added</label>
                <input type="datetime-local" name="date_added" class="form-control" id="date_added" data-tooltip="Specify the date the feed was added">
            </div>
        </div>
        <div class="form-row">
            <div class="form-group col-md-4">
                <label for="last_updated">Last Updated</label>
                <input type="datetime-local" name="last_updated" class="form-control" id="last_updated" data-tooltip="Specify the last update date of the feed">
            </div>
            <div class="form-group col-md-4">
                <label for="is_active">Is Active</label>
                <input type="checkbox" name="is_active" class="form-check-input" id="is_active" data-tooltip="Check if the feed is active">
            </div>
        </div>

        <button type="submit" name="mass_edit" class="btn btn-primary">
            <i class="fas fa-save"></i> Save Changes
            <div id="massEditLoader" class="spinner-border spinner-border-sm ml-2" role="status" style="display: none;"></div>
        </button>
    </form>

<!-- Individual edit form -->
<h3 class="mt-5">Individual Edit</h3>
<form method="post">
    <div class="form-row mb-3">
        <input type="checkbox" id="select-all">
        <label for="select-all" class="ml-2">Select All</label>
    </div>
    <div id="selection-summary">No records selected</div>

    <?php foreach ($results as $row): ?>
        <div class="result-card" id="card_<?= $row['id'] ?>">
            <h4>Record ID: <?= $row['id'] ?></h4>
            <div class="form-row">
                <div class="form-group col-md-1">
                    <input type="checkbox" name="selected_ids[]" value="<?= $row['id'] ?>" class="select-checkbox">
                </div>
                <div class="form-group col-md-6">
                    <label for="website_base_<?= $row['id'] ?>">Website Base</label>
                    <input type="text" name="data[<?= $row['id'] ?>][website_base]" class="form-control" id="website_base_<?= $row['id'] ?>" value="<?= htmlspecialchars($row['website_base']) ?>" data-tooltip="Base URL of the website">
                </div>
                <div class="form-group col-md-6">
                    <label for="website_feed_<?= $row['id'] ?>">Website Feed</label>
                    <input type="text" name="data[<?= $row['id'] ?>][website_feed]" class="form-control" id="website_feed_<?= $row['id'] ?>" value="<?= htmlspecialchars($row['website_feed']) ?>" data-tooltip="Specific feed URL of the website">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group col-md-4">
                    <label for="main_category_id_<?= $row['id'] ?>">Main Category ID</label>
                    <input type="number" name="data[<?= $row['id'] ?>][main_category_id]" class="form-control" id="main_category_id_<?= $row['id'] ?>" value="<?= intval($row['main_category_id']) ?>" data-tooltip="Main category identifier">
                </div>
                <div class="form-group col-md-4">
                    <label for="subcategory_id_<?= $row['id'] ?>">Subcategory ID</label>
                    <input type="number" name="data[<?= $row['id'] ?>][subcategory_id]" class="form-control" id="subcategory_id_<?= $row['id'] ?>" value="<?= intval($row['subcategory_id']) ?>" data-tooltip="Subcategory identifier">
                </div>
                <div class="form-group col-md-4">
                    <label for="subcategory_name_<?= $row['id'] ?>">Subcategory Name</label>
                    <input type="text" name="data[<?= $row['id'] ?>][subcategory_name]" class="form-control" id="subcategory_name_<?= $row['id'] ?>" value="<?= htmlspecialchars($row['subcategory_name']) ?>" data-tooltip="Subcategory name">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group col-md-4">
                    <label for="subsubcategory_id_<?= $row['id'] ?>">Subsubcategory ID</label>
                    <input type="number" name="data[<?= $row['id'] ?>][subsubcategory_id]" class="form-control" id="subsubcategory_id_<?= $row['id'] ?>" value="<?= intval($row['subsubcategory_id']) ?>" data-tooltip="Subsubcategory identifier">
                </div>
                <div class="form-group col-md-4">
                    <label for="subsubcategory_name_<?= $row['id'] ?>">Subsubcategory Name</label>
                    <input type="text" name="data[<?= $row['id'] ?>][subsubcategory_name]" class="form-control" id="subsubcategory_name_<?= $row['id'] ?>" value="<?= htmlspecialchars($row['subsubcategory_name']) ?>" data-tooltip="Subsubcategory name">
                </div>
                <div class="form-group col-md-4">
                    <label for="date_added_<?= $row['id'] ?>">Date Added</label>
                    <input type="datetime-local" name="data[<?= $row['id'] ?>][date_added]" class="form-control" id="date_added_<?= $row['id'] ?>" value="<?= date('Y-m-d\TH:i', strtotime($row['date_added'])) ?>" data-tooltip="Date feed was added">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group col-md-4">
                    <label for="last_updated_<?= $row['id'] ?>">Last Updated</label>
                    <input type="datetime-local" name="data[<?= $row['id'] ?>][last_updated]" class="form-control" id="last_updated_<?= $row['id'] ?>" value="<?= date('Y-m-d\TH:i', strtotime($row['last_updated'])) ?>" data-tooltip="Last updated date of the feed">
                </div>
                <div class="form-group col-md-4">
                    <label for="is_active_<?= $row['id'] ?>">Is Active</label>
                    <input type="checkbox" name="data[<?= $row['id'] ?>][is_active]" class="form-check-input" id="is_active_<?= $row['id'] ?>" <?= $row['is_active'] ? 'checked' : '' ?> data-tooltip="Check if the feed is active">
                </div>
            </div>
            <div class="mt-3 text-right">
                <button type="submit" name="edit_single" value="<?= $row['id'] ?>" class="btn btn-warning">
                    <i class="fas fa-edit"></i> Edit
                </button>
                <a href="shortcut_manager.php?delete_id=<?= $row['id'] ?>" onclick="return confirm('Are you sure?')" class="btn btn-danger">
                    <i class="fas fa-trash"></i> Delete
                </a>
            </div>
        </div>
    <?php endforeach; ?>

    <button type="submit" class="btn btn-primary mt-4">
        <i class="fas fa-save"></i> Save Changes
        <div id="indivEditLoader" class="spinner-border spinner-border-sm ml-2" role="status" style="display: none;"></div>
    </button>
</form>

</div>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script>
    // Show loading indicator when saving
    $('form').on('submit', function () {
        $('#loadingOverlay').addClass('active');
        $('#massEditLoader, #indivEditLoader').show(); // Show loader next to the buttons
    });

    // Select all checkboxes
    $('#select-all').on('click', function() {
        $('.select-checkbox').prop('checked', this.checked);
        updateSelectionSummary();
    });

    // Update selection summary and add selected IDs to hidden field
    $('.select-checkbox').on('change', updateSelectionSummary);

    function updateSelectionSummary() {
        const selectedCheckboxes = $('.select-checkbox:checked');
        const selectedCount = selectedCheckboxes.length;
        $('#selection-summary').text(selectedCount + " records selected");

        // Update hidden field with selected IDs
        let selectedIds = [];
        selectedCheckboxes.each(function() {
            selectedIds.push($(this).val());
        });

        // Update hidden field with selected IDs
        $('#selected_ids_hidden').val(selectedIds.join(','));

        // Add or remove highlight class on selected cards
        $('.result-card').removeClass('selected-card');
        selectedCheckboxes.each(function() {
            $('#card_' + $(this).val()).addClass('selected-card');
        });
    }
</script>

</body>
</html>