<?php foreach($clientProjects as $project):?>
    <div class="card border-0">
        <div class="card-header bg-success bg-opacity-50 fw-bold d-flex justify-content-between">
            <?= $project->name;?>
            <button class="btn btn-sm btn-light small" onclick="edit_project(<?= $project->id; ?>)">Edit Project</button>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <h6 class="fw-bold">Project Brief</h6>
                    <div class="table-responsive">
                        <table class="table table-sm" style="font-size:12px;">
                            <tr>
                                <th>Project ID</th>
                                <td><?= $project->project_number ?: 'undefined'; ?> <button class="btn btn-sm btn-info" onclick="edit_project(<?= $project->id; ?>)"><i class="bi bi-pencil"></i></button></td>
                            </tr>
                            <tr>
                                <th>Area (Ha)</th><td><?= $project->size; ?>ha</td>
                            </tr>
                            <tr>
                                <th>Location</th><td><?= $project->location_description; ?></td>
                            </tr>
                            <tr>
                                <th>District</th><td><?= $project->district_name; ?></td>
                            </tr>
                            <tr>
                                <th>County</th><td><?= $project->county_name; ?></td>
                            </tr>
                            <tr>
                                <th>Sub-County</th><td><?= $project->subcounty_name; ?></td>
                            </tr>
                            <tr>
                                <th>Parish</th><td><?= $project->parish_name; ?></td>
                            </tr>
                            <tr>
                                <th>Village</th><td><?= $project->village_name; ?></td>
                            </tr>
                        </table>
                    </div>
                </div>
                <div class="col-md-6 mb-3">
                    <?php if(!empty($singleCarbonData)):?>
                    <div class="d-flex justify-content-between">
                        <h6 class="fw-bold">Current Carbon Data</h6>
                        <button class="btn btn-sm btn-info" title="Edit Carbon Data" onclick="edit_carbon_data(<?= $singleCarbonData->id;?>)"><i class="bi bi-pencil small"></i> </button>
                    </div>
                    
                    <div class="table-responsive">
                        <table class="table table-sm" style="font-size:12px;">
                            <tr><th>Project Status</th>
                                <td>
                                    <?php if (!empty($project->singleStatus)): ?>
                                        <span class="badge" 
                                              style="background-color: <?= esc($project->singleStatus->status_color) ?>;">
                                            <i class="<?= esc($project->singleStatus->status_icon) ?> me-2"></i>
                                            <?= esc($project->singleStatus->status_name) ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="badge bg-secondary">No Status</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr><th>Estimated ER</th><td><?= number_format($singleCarbonData->estimated_er); ?></td></tr>
                            <tr><th>Buffer Credit</th><td><?= number_format($singleCarbonData->buffer_credit); ?></td></tr>
                            <tr><th>Credit Period</th><td><?= date('Y', strtotime($singleCarbonData->credit_period_start)); ?> to <?= date('Y', strtotime($singleCarbonData->credit_period_end)); ?></td></tr>
                            <tr><th>Reff Period</th><td><?= date('Y', strtotime($singleCarbonData->reff_period_start)); ?> to <?= date('Y', strtotime($singleCarbonData->reff_period_end)); ?></td></tr>
                            <tr><th>Uncertainty</th><td><?= $singleCarbonData->uncertainty; ?></td></tr>
                            <tr><th>Registry</th><td><?=  $singleCarbonData->registry; ?></td></tr>
                        </table>
                    </div>
                    <?php endif;?>
                </div>
            </div><!-- End Row !-->
            <div class="alert bg-primary bg-opacity-10 shadow-sm mb-3">
                <div class="d-flex justify-content-between">
                    <h6 class="fw-bold">Program / Project Type</h6>
                    <button class="btn btn-sm btn-secondary" onclick="editProjectItem(<?= $project->id ?>, 'types')"><i class="bi bi-pencil small"></i></button>
                </div>
                <small>
                <?php if (!empty($project->types)): ?>
                    <ul type="none">
                        <?php foreach ($project->types as $type): ?>
                            <li>
                                <i class="bi bi-check"></i> <?= esc($type->type_name) ?>
                                <span><button class="btn btn-sm btn-transparent small" title="Delete" onclick="delete_item(<?= $type->id ?>, 'types')"><i class="bi bi-x-circle-fill text-danger small"></i></button></span>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php else: ?>
                    <p>No Project Types listed.</p>
                <?php endif; ?>
                </small>
            </div><!-- Program / Project Type!-->
            <div class="alert bg-info bg-opacity-10 shadow-sm mb-3">
                <div class="d-flex justify-content-between">
                    <h6 class="fw-bold">AFOLU Activities</h6>
                    <button class="btn btn-sm btn-secondary" onclick="editProjectItem(<?= $project->id ?>, 'activities')"><i class="bi bi-pencil small"></i></button>
                </div>
                <small>
                <?php if (!empty($project->activities)): ?>
                    <ul type="none">
                        <?php foreach ($project->activities as $activity): ?>
                            <li>
                                <i class="bi bi-check"></i> <?= esc($activity->activity_name) ?>
                                <span><button class="btn btn-sm btn-transparent small" title="Delete" onclick="delete_item(<?= $activity->id ?>, 'activities')"><i class="bi bi-x-circle-fill text-danger small"></i></button></span>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php else: ?>
                    <p>No activities listed.</p>
                <?php endif; ?>
                </small>
            </div><!-- activities !-->
            <div class="alert bg-warning bg-opacity-10 shadow-sm mb-3">
                <div class="d-flex justify-content-between">
                    <h6 class="fw-bold">Methodologies</h6>
                    <button class="btn btn-sm btn-secondary" onclick="editProjectItem(<?= $project->id ?>, 'methodologies')"><i class="bi bi-pencil small"></i></button>
                </div>
                <small>
                <?php if (!empty($project->methodologies)): ?>
                    <ul type="none">
                        <?php foreach ($project->methodologies as $methodology): ?>
                            <li>
                                <i class="bi bi-check"></i> <?= esc($methodology->name) ?>
                                <span><button class="btn btn-sm btn-transparent small" title="Delete" onclick="delete_item(<?= $methodology->id ?>, 'methodologies')"><i class="bi bi-x-circle-fill text-danger small"></i></button></span>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php else: ?>
                    <p>No Methodologies listed.</p>
                <?php endif; ?>
                </small>
            </div><!-- Methodologies !-->

            <div class="alert bg-primary bg-opacity-10 shadow-sm mb-3">
                <div class="d-flex justify-content-between">
                    <h6 class="fw-bold">Project Carbon Pools</h6>
                    <button class="btn btn-sm btn-secondary" onclick="editProjectItem(<?= $project->id ?>, 'carbon-pools')"><i class="bi bi-pencil small"></i></button>
                </div>
                <small>
                <?php if (!empty($project->carbon_pools)): ?>
                    <ul type="none">
                        <?php foreach ($project->carbon_pools as $carbon): ?>
                            <li>
                                <i class="bi bi-check"></i> <?= esc($carbon->name) ?>
                                <span><button class="btn btn-sm btn-transparent small" title="Delete" onclick="delete_item(<?= $carbon->id ?>, 'carbon-pools')"><i class="bi bi-x-circle-fill text-danger small"></i></button></span>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php else: ?>
                    <p>No Carbon Pools listed.</p>
                <?php endif; ?>
                </small>
            </div><!-- Carbon Pools !-->

            <div class="alert bg-danger bg-opacity-10 shadow-sm mb-3">
                <div class="d-flex justify-content-between">
                    <h6 class="fw-bold">Project Gases</h6>
                    <button class="btn btn-sm btn-secondary" onclick="editProjectItem(<?= $project->id ?>, 'gases')">
                        <i class="bi bi-pencil small"></i>
                    </button>
                </div>
                <small>
                <?php if (!empty($project->gases)): ?>
                    <ul type="none">
                        <?php foreach ($project->gases as $gas): ?>
                            <li><i class="bi bi-check"></i> <?= esc($gas->name) ?> <small>(<?= $gas->symbol ?>) <span><button class="btn btn-sm btn-transparent small" title="Delete" onclick="delete_item(<?= $gas->id ?>, 'gases')"><i class="bi bi-x-circle-fill text-danger small"></i></button></span></small></li>
                        <?php endforeach; ?>
                    </ul>
                <?php else: ?>
                    <p>No Gases listed.</p>
                <?php endif; ?>
                </small>
            </div><!-- Gases !-->
            
        </div>
    </div>
<?php endforeach;?>


<!-- Modal  Modal -->
<div class="modal fade" id="projectItemModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 id="modalTitle" class="modal-title">Edit Item</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <form id="projectItemForm" method="POST" action="<?= base_url('administrator/redd/projects/save-items'); ?>">
          <?= csrf_field(); ?>
          <input type="hidden" name="project_id" id="project_id">
          <input type="hidden" name="type" id="item_type"> <!-- gases, activities -->
          
          <div id="itemFields"><!-- dynamic inputs will be injected here --></div>
            
          <!-- Project Types !-->
           <div class="mb-3 type-section" id="projectType" style="display:none">
            <table class="table table-sm" id="typesList">
                <thead><tr><th>Type</th><th>Action</th></tr></thead>
                <tbody></tbody>
            </table>
                <label for="newType" class="form-label">Add Type</label>
                <div class="input-group">
                    <select id="newType" class="form-select">
                        <option value="">-- Select an Type --</option>
                        <?php foreach ($types as $at): ?>
                            <option value="<?= $at->id ?>"><?= esc($at->name) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <button type="button" id="btnAddType" class="btn btn-sm btn-primary">Add</button>
                </div>
            </div>
          <!-- End Project Types !-->
          <!-- Activity !-->
           <div class="mb-3 type-section" id="projectActivity" style="display:none">
            <table class="table table-sm" id="activitiesList">
                <thead><tr><th>Activity</th><th>Action</th></tr></thead>
                <tbody></tbody>
            </table>
                <label for="newActivity" class="form-label">Add Activity</label>
                <div class="input-group">
                    <select id="newActivity" class="form-select">
                        <option value="">-- Select an Activity --</option>
                        <?php foreach ($activities as $at): ?>
                            <option value="<?= $at->id ?>"><?= esc($at->name) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <button type="button" id="btnAddActivity" class="btn btn-sm btn-primary">Add</button>
                </div>
            </div>
          <!-- End Activity !-->
          <!-- Methodology !-->
           <div class="mb-3 type-section" id="projectMethodology" style="display:none">
            <table class="table table-sm" id="methodologiesList">
                <thead><tr><th>Methodology</th><th>Action</th></tr></thead>
                <tbody></tbody>
            </table>
                <label for="newMethodology" class="form-label">Add Methodology</label>
                <div class="input-group">
                    <select id="newMethodology" class="form-select">
                        <option value="">-- Select an Methodology --</option>
                        <?php foreach ($methodologies as $at): ?>
                            <option value="<?= $at->id ?>"><?= esc($at->name) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <button type="button" id="btnAddMethodology" class="btn btn-sm btn-primary">Add</button>
                </div>
            </div>
          <!-- Methodology !-->
          <!-- Gases !-->
           <div class="mb-3 type-section" id="projectGas" style="display:none">
            <table class="table table-sm" id="gasesList">
                <thead><tr><th>Gas</th><th>Action</th></tr></thead>
                <tbody></tbody>
            </table>
                <label for="newGas" class="form-label">Add Activity</label>
                <div class="input-group">
                    <select id="newGas" class="form-select">
                        <option value="">-- Select an Gas --</option>
                        <?php foreach ($gases as $at): ?>
                            <option value="<?= $at->id ?>"><?= esc($at->name) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <button type="button" id="btnAddGas" class="btn btn-sm btn-primary">Add</button>
                </div>
            </div>
          <!-- End Gases !-->
           <!-- Carbon Pools !-->
           <div class="mb-3 type-section" id="projectCarbonPool" style="display:none">
            <table class="table table-sm" id="poolsList">
                <thead><tr><th>Carbon Pool</th><th>Action</th></tr></thead>
                <tbody></tbody>
            </table>
                <label for="newPool" class="form-label">Add Carbon Pool</label>
                <div class="input-group">
                    <select id="newPool" class="form-select">
                        <option value="">-- Select an Gas --</option>
                        <?php foreach ($carbon_pools as $at): ?>
                            <option value="<?= $at->id ?>"><?= esc($at->name) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <button type="button" id="btnAddPool" class="btn btn-sm btn-primary">Add</button>
                </div>
            </div>
          <!-- End Carbon Pool !-->
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" onclick="saveProjectItem()">Save</button>
      </div>
    </div>
  </div>
</div>

<script>
    $(document).ready(function(){
        
    });


    function editProjectItem(projectId, type) {
    $('#project_id').val(projectId);
    $('#item_type').val(type);
    $('#modalTitle').text("Edit Project " + type.charAt(0).toUpperCase() + type.slice(1));

     // hide all type sections first
    $('.type-section').hide();

    // then show only the one for this type
    if (type === 'activities') {
        $('#projectActivity').show();
        $("#btnAddActivity").on("click", function()
        {
            var id   = $("#newActivity").val();
            var name = $("#newActivity option:selected").text();

            if(id) {
                // append to your results table/list
                $("#activitiesList").append(
                    `<tr><input type="hidden" name="activity_id[]" value="${id}">
                        <td>${name}</td>
                        <td>
                            <button type="button" class="btn btn-danger btn-sm removeRow">Remove</button>
                        </td>
                    </tr>`
                );
                $("#newActivity").val(""); // reset dropdown
            }
        });
        $(document).on("click", ".removeRow", function(){
            $(this).closest("tr").remove();
        });
    } else if (type === 'types') {
        $('#projectType').show();
        $("#btnAddType").on("click", function()
        {
            var id   = $("#newType").val();
            var name = $("#newType option:selected").text();

            if(id) {
                // append to your results table/list
                $("#typesList").append(
                    `<tr><input type="hidden" name="activity_id[]" value="${id}">
                        <td>${name}</td>
                        <td>
                            <button type="button" class="btn btn-danger btn-sm removeRow">Remove</button>
                        </td>
                    </tr>`
                );
                $("#newType").val(""); // reset dropdown
            }
        });
        $(document).on("click", ".removeRow", function(){
            $(this).closest("tr").remove();
        });
    } else if (type === 'methodologies') {
        $('#projectMethodology').show();
        $("#btnAddMethodology").on("click", function()
        {
            var id   = $("#newMethodology").val();
            var name = $("#newMethodology option:selected").text();

            if(id) {
                // append to your results table/list
                $("#methodologiesList").append(
                    `<tr><input type="hidden" name="activity_id[]" value="${id}">
                        <td>${name}</td>
                        <td>
                            <button type="button" class="btn btn-danger btn-sm removeRow">Remove</button>
                        </td>
                    </tr>`
                );
                $("#newMethodology").val(""); // reset dropdown
            }
        });
        $(document).on("click", ".removeRow", function(){
            $(this).closest("tr").remove();
        });
    } else if (type === 'carbon-pools') {
        $('#projectCarbonPool').show();
        $("#btnAddPool").on("click", function()
        {
            var id   = $("#newPool").val();
            var name = $("#newPool option:selected").text();

            if(id) {
                // append to your results table/list
                $("#poolsList").append(
                    `<tr><input type="hidden" name="activity_id[]" value="${id}">
                        <td>${name}</td>
                        <td>
                            <button type="button" class="btn btn-danger btn-sm removeRow">Remove</button>
                        </td>
                    </tr>`
                );
                $("#newPool").val(""); // reset dropdown
            }
        });
        $(document).on("click", ".removeRow", function(){
            $(this).closest("tr").remove();
        });
    } else if (type === 'gases') {
        $('#projectGas').show();
        $("#btnAddGas").on("click", function()
        {
            var id   = $("#newGas").val();
            var name = $("#newGas option:selected").text();

            if(id) {
                // append to your results table/list
                $("#gasesList").append(
                    `<tr><input type="hidden" name="activity_id[]" value="${id}">
                        <td>${name}</td>
                        <td>
                            <button type="button" class="btn btn-danger btn-sm removeRow">Remove</button>
                        </td>
                    </tr>`
                );
                $("#newGas").val(""); // reset dropdown
            }
        });
        $(document).on("click", ".removeRow", function(){
            $(this).closest("tr").remove();
        });
    }

    $.get(base_url + 'administrator/redd/projects/get-items/' + projectId + '/' + type, function(items) {
        let html = '';

        items.forEach((item, i) => {
            html += `
                <div class="input-group mb-2">
                    <input type="hidden" name="activity_id[]" value="${item.id}">
                    <input type="text" class="form-control" value="${item.name}" readonly>
                    <button type="button" class="btn btn-danger" onclick="$(this).closest('.input-group').remove()">x</button>
                </div>`;
        });


        $('#itemFields').html(html);
        $('#projectItemModal').modal('show');
    }, 'json'); // tell jQuery we expect JSON

}

function saveProjectItem() {
    $.post(base_url + 'administrator/redd/projects/save-items', $('#projectItemForm').serialize(), function(resp) {
        location.reload(); // refresh page to show updates
    });
}

function delete_item(id, type){
    var confirmation = confirm('Are you sure want to delete this? ' + type);
    if(confirmation == true){
        window.location.href = base_url + ('administrator/redd/delete-item/')+ type +'/'+ id;
    }
}

</script>



