@extends('admin.admin_master')
@section('admin')

<div class="page-content">
    <div class="container-fluid">
        <div class="row mb-4">
            <div class="col-12">
                <div class="page-header-card">
                    <div class="page-header-content">
                        <div class="d-flex align-items-center justify-content-between flex-wrap gap-3">
                            <div class="d-flex align-items-center">
                                <div class="page-icon me-3">
                                    <div class="avatar-md">
                                        <div class="avatar-title bg-primary-subtle text-primary rounded-circle">
                                            <i class="ri-file-list-3-line font-size-24"></i>
                                        </div>
                                    </div>
                                </div>
                                <div class="flex-grow-1">
                                    <h4 class="page-title mb-1">Department Setup Questionnaire</h4>
                                    <p class="page-subtitle text-muted mb-0">
                                        Collect users, folder structure, access permissions, and workflow routing before go-live.
                                    </p>
                                </div>
                            </div>
                            <div class="d-flex gap-2">
                                <a href="{{ route('workflow.department-setup-questionnaire.submissions') }}" class="btn btn-outline-primary">
                                    <i class="ri-database-2-line me-1"></i>View Saved Submissions
                                </a>
                                <a href="{{ route('workflow.department-setup-questionnaire.export-csv') }}" class="btn btn-outline-success">
                                    <i class="ri-file-excel-2-line me-1"></i>Export CSV (Excel/Sheets)
                                </a>
                                <button type="button" class="btn btn-outline-secondary" onclick="window.print()">
                                    <i class="ri-printer-line me-1"></i>Print / Save as PDF
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-12">
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-body">
                        <h5 class="card-title mb-3">Instructions</h5>
                        <ul class="text-muted mb-0">
                            <li>Complete one form per department.</li>
                            <li>Add all staff who need access at launch.</li>
                            <li>Use the permission checklist to define exactly what each user can do in each folder.</li>
                            <li>For workflows, list all steps from initiator to final approval and confirm the final step returns to the initiator.</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>

        @if(session('message'))
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                {{ session('message') }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        @endif

        @if($errors->any())
            <div class="alert alert-danger" role="alert">
                <strong>Please correct the highlighted fields.</strong>
            </div>
        @endif

        <form method="POST" action="{{ route('workflow.department-setup-questionnaire.store') }}" id="department-setup-questionnaire-form">
            @csrf
            <input type="hidden" name="users_json" id="users_json" />
            <input type="hidden" name="folders_json" id="folders_json" />
            <input type="hidden" name="permissions_matrix_json" id="permissions_matrix_json" />
            <input type="hidden" name="workflows_json" id="workflows_json" />
            <div class="row">
                <div class="col-lg-6">
                    <div class="card border-0 shadow-sm mb-4">
                        <div class="card-header bg-light">
                            <h5 class="mb-0">1) Department Information</h5>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label class="form-label">Department Name</label>
                                <input type="text" name="department_name" value="{{ old('department_name') }}" class="form-control @error('department_name') is-invalid @enderror" placeholder="Example: Marketing" required />
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Department Head(s)</label>
                                <input type="text" name="department_heads" value="{{ old('department_heads') }}" class="form-control" placeholder="Enter one or multiple names" />
                            </div>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Primary Contact Email</label>
                                    <input type="email" name="primary_contact_email" value="{{ old('primary_contact_email') }}" class="form-control" placeholder="name@company.com" />
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Primary Contact Phone</label>
                                    <input type="text" name="primary_contact_phone" value="{{ old('primary_contact_phone') }}" class="form-control" placeholder="Optional" />
                                </div>
                            </div>
                            <div class="mb-0">
                                <label class="form-label">Go-Live Priority Notes</label>
                                <textarea name="go_live_priority_notes" class="form-control" rows="3" placeholder="Any special setup priorities or deadlines">{{ old('go_live_priority_notes') }}</textarea>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-lg-6">
                    <div class="card border-0 shadow-sm mb-4">
                        <div class="card-header bg-light">
                            <h5 class="mb-0">2) Department Users</h5>
                        </div>
                        <div class="card-body">
                            <p class="text-muted mb-3">Add all users in this department who require access.</p>
                            <div id="users-container"></div>
                            <button type="button" class="btn btn-outline-primary btn-sm" id="add-user-btn">
                                <i class="ri-user-add-line me-1"></i>Add User
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-12">
                    <div class="card border-0 shadow-sm mb-4">
                        <div class="card-header bg-light d-flex justify-content-between align-items-center flex-wrap gap-2">
                            <h5 class="mb-0">3) Main Folder Structure Required</h5>
                            <button type="button" class="btn btn-outline-primary btn-sm" id="add-folder-btn">
                                <i class="ri-folder-add-line me-1"></i>Add Folder
                            </button>
                        </div>
                        <div class="card-body">
                            <div id="folders-container"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-12">
                    <div class="card border-0 shadow-sm mb-4">
                        <div class="card-header bg-light">
                            <h5 class="mb-0">4) Folder Access and Permissions Matrix</h5>
                        </div>
                        <div class="card-body">
                            <p class="text-muted mb-3">For each user and folder, tick the permissions required at go-live.</p>
                            <div class="table-responsive">
                                <table class="table table-bordered align-middle">
                                    <thead class="table-light">
                                        <tr>
                                            <th style="min-width: 200px;">User Name</th>
                                            <th style="min-width: 220px;">Folder Name</th>
                                            <th>Access Shared Folders</th>
                                            <th>Create My Folder (Create Subfolders)</th>
                                            <th>View Folder</th>
                                            <th>View Folder Contents</th>
                                            <th>Manage Folder Permissions</th>
                                            <th>Upload My Files</th>
                                            <th>Download My Files</th>
                                            <th>Delete My Files</th>
                                            <th>Share Folder</th>
                                        </tr>
                                    </thead>
                                    <tbody id="permission-matrix-body"></tbody>
                                </table>
                            </div>
                            <button type="button" class="btn btn-outline-primary btn-sm" id="add-permission-row-btn">
                                <i class="ri-add-line me-1"></i>Add User/Folder Permission Row
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-12">
                    <div class="card border-0 shadow-sm mb-4">
                        <div class="card-header bg-light d-flex justify-content-between align-items-center flex-wrap gap-2">
                            <h5 class="mb-0">5) Workflow Definitions</h5>
                            <button type="button" class="btn btn-outline-primary btn-sm" id="add-workflow-btn">
                                <i class="ri-flow-chart me-1"></i>Add Workflow
                            </button>
                        </div>
                        <div class="card-body">
                            <p class="text-muted mb-3">
                                Capture each workflow from initiating staff to final approval and include the return-to-initiator step.
                            </p>
                            <div id="workflows-container"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-12">
                    <div class="card border-0 shadow-sm mb-4">
                        <div class="card-header bg-light">
                            <h5 class="mb-0">6) Final Confirmation</h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Completed By</label>
                                    <input type="text" name="completed_by" value="{{ old('completed_by') }}" class="form-control" placeholder="Name" />
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Date Completed</label>
                                    <input type="date" name="completed_date" value="{{ old('completed_date') }}" class="form-control" />
                                </div>
                            </div>
                            <div class="mb-0">
                                <label class="form-label">Additional Notes</label>
                                <textarea name="additional_notes" class="form-control" rows="4" placeholder="Any other details to support setup">{{ old('additional_notes') }}</textarea>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-12 d-flex justify-content-end mb-4">
                    <button type="submit" class="btn btn-primary">
                        <i class="ri-save-line me-1"></i>Save Questionnaire
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
(function () {
    function createRemoveButton() {
        var btn = document.createElement('button');
        btn.type = 'button';
        btn.className = 'btn btn-sm btn-outline-danger';
        btn.innerHTML = '<i class="ri-delete-bin-line"></i>';
        btn.addEventListener('click', function () {
            var row = btn.closest('[data-repeat-row]');
            if (row) {
                row.remove();
            }
        });
        return btn;
    }

    function addUserRow() {
        var container = document.getElementById('users-container');
        if (!container) {
            return;
        }

        var row = document.createElement('div');
        row.className = 'border rounded p-3 mb-3';
        row.setAttribute('data-repeat-row', 'user');
        row.innerHTML = '' +
            '<div class="row g-2 align-items-end">' +
                '<div class="col-md-3"><label class="form-label">Full Name</label><input type="text" class="form-control user-name" placeholder="Full name"></div>' +
                '<div class="col-md-3"><label class="form-label">Email</label><input type="email" class="form-control user-email" placeholder="name@company.com"></div>' +
                '<div class="col-md-2"><label class="form-label">Job Title</label><input type="text" class="form-control user-title" placeholder="Title"></div>' +
                '<div class="col-md-2"><label class="form-label">Department Role</label><input type="text" class="form-control user-role" placeholder="Staff / Head / Deputy"></div>' +
                '<div class="col-md-2"><label class="form-label">Line Manager</label><input type="text" class="form-control user-manager" placeholder="Manager name"></div>' +
            '</div>';

        var removeWrap = document.createElement('div');
        removeWrap.className = 'mt-2 d-flex justify-content-end';
        removeWrap.appendChild(createRemoveButton());
        row.appendChild(removeWrap);
        container.appendChild(row);
    }

    function addFolderRow() {
        var container = document.getElementById('folders-container');
        if (!container) {
            return;
        }

        var row = document.createElement('div');
        row.className = 'border rounded p-3 mb-3';
        row.setAttribute('data-repeat-row', 'folder');
        row.innerHTML = '' +
            '<div class="row g-2 align-items-end">' +
                '<div class="col-md-3"><label class="form-label">Main Folder Name</label><input type="text" class="form-control folder-name" placeholder="Example: Marketing Campaigns"></div>' +
                '<div class="col-md-2"><label class="form-label">Parent Folder</label><input type="text" class="form-control folder-parent" placeholder="Root or parent"></div>' +
                '<div class="col-md-2"><label class="form-label">Owner</label><input type="text" class="form-control folder-owner" placeholder="Owner name"></div>' +
                '<div class="col-md-2"><label class="form-label">Confidentiality</label><select class="form-select folder-confidentiality"><option>Public</option><option>Internal</option><option>Confidential</option><option>Restricted</option></select></div>' +
                '<div class="col-md-3"><label class="form-label">Notes</label><input type="text" class="form-control folder-notes" placeholder="Usage or document type"></div>' +
            '</div>';

        var removeWrap = document.createElement('div');
        removeWrap.className = 'mt-2 d-flex justify-content-end';
        removeWrap.appendChild(createRemoveButton());
        row.appendChild(removeWrap);
        container.appendChild(row);
    }

    function addPermissionRow() {
        var tbody = document.getElementById('permission-matrix-body');
        if (!tbody) {
            return;
        }

        var tr = document.createElement('tr');
        tr.setAttribute('data-repeat-row', 'permission');
        tr.innerHTML = '' +
            '<td><input type="text" class="form-control permission-user" placeholder="User name"></td>' +
            '<td><input type="text" class="form-control permission-folder" placeholder="Folder name"></td>' +
            '<td class="text-center"><input type="checkbox" class="form-check-input perm-access-shared"></td>' +
            '<td class="text-center"><input type="checkbox" class="form-check-input perm-create-subfolders"></td>' +
            '<td class="text-center"><input type="checkbox" class="form-check-input perm-view-folder"></td>' +
            '<td class="text-center"><input type="checkbox" class="form-check-input perm-view-contents"></td>' +
            '<td class="text-center"><input type="checkbox" class="form-check-input perm-manage-permissions"></td>' +
            '<td class="text-center"><input type="checkbox" class="form-check-input perm-upload"></td>' +
            '<td class="text-center"><input type="checkbox" class="form-check-input perm-download"></td>' +
            '<td class="text-center"><input type="checkbox" class="form-check-input perm-delete-files"></td>' +
            '<td class="text-center"><input type="checkbox" class="form-check-input perm-share-folder"></td>';

        var removeCell = document.createElement('td');
        removeCell.className = 'text-center';
        removeCell.appendChild(createRemoveButton());
        tr.appendChild(removeCell);
        tbody.appendChild(tr);

        var thRow = tbody.closest('table').querySelector('thead tr');
        if (thRow && thRow.children.length === 11) {
            var th = document.createElement('th');
            th.textContent = 'Remove';
            thRow.appendChild(th);
        }
    }

    function addWorkflowStep(container) {
        var stepsContainer = container.querySelector('[data-steps-container]');
        if (!stepsContainer) {
            return;
        }

        var row = document.createElement('div');
        row.className = 'row g-2 align-items-end mb-2';
        row.setAttribute('data-repeat-row', 'step');
        row.innerHTML = '' +
            '<div class="col-md-2"><label class="form-label">Step #</label><input type="number" class="form-control step-number" min="1" placeholder="1"></div>' +
            '<div class="col-md-3"><label class="form-label">From (Role/User)</label><input type="text" class="form-control step-from" placeholder="Staff / Dept Head"></div>' +
            '<div class="col-md-3"><label class="form-label">To (Role/User)</label><input type="text" class="form-control step-to" placeholder="Dept Head / CEO / Deputy"></div>' +
            '<div class="col-md-3"><label class="form-label">Step Rule</label><input type="text" class="form-control step-rule" placeholder="Approval, Review, Edit, FYI"></div>' +
            '<div class="col-md-1 d-flex justify-content-end"></div>';

        var removeTarget = row.querySelector('.col-md-1');
        removeTarget.appendChild(createRemoveButton());
        stepsContainer.appendChild(row);
    }

    function addWorkflowCard() {
        var container = document.getElementById('workflows-container');
        if (!container) {
            return;
        }

        var card = document.createElement('div');
        card.className = 'border rounded p-3 mb-3';
        card.setAttribute('data-repeat-row', 'workflow');
        card.innerHTML = '' +
            '<div class="row g-2 mb-2">' +
                '<div class="col-md-4"><label class="form-label">Workflow Name</label><input type="text" class="form-control workflow-name" placeholder="Example: Marketing Budget Approval"></div>' +
                '<div class="col-md-4"><label class="form-label">Initiated By</label><input type="text" class="form-control workflow-initiated-by" placeholder="Staff role(s) who start this workflow"></div>' +
                '<div class="col-md-4"><label class="form-label">Department Head(s) in Workflow</label><input type="text" class="form-control workflow-heads" placeholder="List names if multiple"></div>' +
            '</div>' +
            '<div data-steps-container></div>' +
            '<div class="d-flex justify-content-between align-items-center mt-2">' +
                '<button type="button" class="btn btn-outline-primary btn-sm" data-add-step-btn><i class="ri-git-commit-line me-1"></i>Add Step</button>' +
                '<div class="form-check mb-0">' +
                    '<input class="form-check-input workflow-return" type="checkbox" id="return_to_initiator_' + Date.now() + Math.floor(Math.random() * 1000) + '">' +
                    '<label class="form-check-label">Final step returns to initiating staff member</label>' +
                '</div>' +
            '</div>';

        var footer = document.createElement('div');
        footer.className = 'd-flex justify-content-end mt-3';
        footer.appendChild(createRemoveButton());
        card.appendChild(footer);

        container.appendChild(card);

        var stepButton = card.querySelector('[data-add-step-btn]');
        if (stepButton) {
            stepButton.addEventListener('click', function () {
                addWorkflowStep(card);
            });
        }

        addWorkflowStep(card);
    }

    var addUserBtn = document.getElementById('add-user-btn');
    if (addUserBtn) {
        addUserBtn.addEventListener('click', addUserRow);
    }

    var addFolderBtn = document.getElementById('add-folder-btn');
    if (addFolderBtn) {
        addFolderBtn.addEventListener('click', addFolderRow);
    }

    var addPermissionBtn = document.getElementById('add-permission-row-btn');
    if (addPermissionBtn) {
        addPermissionBtn.addEventListener('click', addPermissionRow);
    }

    var addWorkflowBtn = document.getElementById('add-workflow-btn');
    if (addWorkflowBtn) {
        addWorkflowBtn.addEventListener('click', addWorkflowCard);
    }

    function valueOf(el, selector) {
        var node = el.querySelector(selector);
        return node ? node.value.trim() : '';
    }

    function checkedOf(el, selector) {
        var node = el.querySelector(selector);
        return !!(node && node.checked);
    }

    var form = document.getElementById('department-setup-questionnaire-form');
    if (form) {
        form.addEventListener('submit', function () {
            var users = Array.prototype.slice.call(document.querySelectorAll('[data-repeat-row="user"]')).map(function (row) {
                return {
                    name: valueOf(row, '.user-name'),
                    email: valueOf(row, '.user-email'),
                    title: valueOf(row, '.user-title'),
                    department_role: valueOf(row, '.user-role'),
                    line_manager: valueOf(row, '.user-manager')
                };
            }).filter(function (u) { return u.name || u.email || u.title || u.department_role || u.line_manager; });

            var folders = Array.prototype.slice.call(document.querySelectorAll('[data-repeat-row="folder"]')).map(function (row) {
                return {
                    name: valueOf(row, '.folder-name'),
                    parent: valueOf(row, '.folder-parent'),
                    owner: valueOf(row, '.folder-owner'),
                    confidentiality: valueOf(row, '.folder-confidentiality'),
                    notes: valueOf(row, '.folder-notes')
                };
            }).filter(function (f) { return f.name || f.parent || f.owner || f.confidentiality || f.notes; });

            var permissions = Array.prototype.slice.call(document.querySelectorAll('[data-repeat-row="permission"]')).map(function (row) {
                return {
                    user_name: valueOf(row, '.permission-user'),
                    folder_name: valueOf(row, '.permission-folder'),
                    access_shared_folders: checkedOf(row, '.perm-access-shared'),
                    create_my_folder: checkedOf(row, '.perm-create-subfolders'),
                    view_folder: checkedOf(row, '.perm-view-folder'),
                    view_folder_contents: checkedOf(row, '.perm-view-contents'),
                    manage_folder_permissions: checkedOf(row, '.perm-manage-permissions'),
                    upload_my_files: checkedOf(row, '.perm-upload'),
                    download_my_files: checkedOf(row, '.perm-download'),
                    delete_my_files: checkedOf(row, '.perm-delete-files'),
                    share_folder: checkedOf(row, '.perm-share-folder')
                };
            }).filter(function (p) { return p.user_name || p.folder_name; });

            var workflows = Array.prototype.slice.call(document.querySelectorAll('[data-repeat-row="workflow"]')).map(function (card) {
                var steps = Array.prototype.slice.call(card.querySelectorAll('[data-repeat-row="step"]')).map(function (row) {
                    return {
                        step_number: valueOf(row, '.step-number'),
                        from: valueOf(row, '.step-from'),
                        to: valueOf(row, '.step-to'),
                        rule: valueOf(row, '.step-rule')
                    };
                }).filter(function (s) { return s.step_number || s.from || s.to || s.rule; });

                return {
                    workflow_name: valueOf(card, '.workflow-name'),
                    initiated_by: valueOf(card, '.workflow-initiated-by'),
                    department_heads: valueOf(card, '.workflow-heads'),
                    final_returns_to_initiator: checkedOf(card, '.workflow-return'),
                    steps: steps
                };
            }).filter(function (w) { return w.workflow_name || w.initiated_by || w.department_heads || w.steps.length > 0; });

            document.getElementById('users_json').value = JSON.stringify(users);
            document.getElementById('folders_json').value = JSON.stringify(folders);
            document.getElementById('permissions_matrix_json').value = JSON.stringify(permissions);
            document.getElementById('workflows_json').value = JSON.stringify(workflows);
        });
    }

    addUserRow();
    addFolderRow();
    addPermissionRow();
    addWorkflowCard();
})();
</script>

@endsection
