<?php
include "check_login.php";
include "dbcon.php";

$phase_id   = (int)$_GET['phase_id'];
$project_id = (int)$_GET['project_id'];

/* Phase info */
$phase = mysqli_fetch_assoc(mysqli_query($conn,"
    SELECT * FROM project_phases
    WHERE id=$phase_id AND project_id=$project_id
"));

/* Reports */
$reports = mysqli_query($conn,"
    SELECT * FROM phase_reports
    WHERE phase_id=$phase_id
    ORDER BY id DESC
");
?>

<!DOCTYPE html>
<html lang="zxx">
<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  
    <title>Leads</title>
  
    <link rel="shortcut icon" type="image/x-icon" href="assets/images/favicon.ico">
  
    <link rel="stylesheet" type="text/css" href="assets/css/bootstrap.min.css">
 
    <link rel="stylesheet" type="text/css" href="assets/vendors/css/vendors.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendors/css/select2.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendors/css/select2-theme.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendors/css/datepicker.min.html">
    
    <link rel="stylesheet" type="text/css" href="assets/css/theme.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

</head>

<body>
<?php include("sidebar.php"); ?>
<?php include("header.php"); ?>   

    <main class="nxl-container">
        <div class="nxl-content">
            <!-- [ page-header ] start -->
            <div class="page-header">
                <div class="page-header-left d-flex align-items-center">
                    <div class="page-header-title">
                        <h5 class="m-b-10">Leads</h5>
                    </div>
                    <ul class="breadcrumb">
                        <li class="breadcrumb-item"><a href="index.html">Home</a></li>
                        <li class="breadcrumb-item">View</li>
                    </ul>
                </div>
      
            </div>
            <!-- [ page-header ] end -->
          
            <!-- [ Main Content ] start -->
            <div class="main-content">
   <?php if(mysqli_num_rows($reports) > 0){ ?>

<?php while($r = mysqli_fetch_assoc($reports)){ ?>

<div class="card mb-3">
    <div class="card-body">

        <div class="d-flex justify-content-between align-items-start mb-2">
            <div>
                <strong><?= date('d M Y, h:i A', strtotime($r['created_at'])) ?></strong>
                <div class="fs-12 text-muted mt-1">
                    <?= nl2br(htmlspecialchars($r['remarks'])); ?>
                </div>
            </div>

            <a href="../uploads/phase_reports/<?= urlencode($r['report_file']) ?>"
               target="_blank"
               class="btn btn-sm btn-outline-primary">
                <i class="feather-download"></i> Download
            </a>
        </div>

    </div>
</div>

<?php } ?>

<?php } else { ?>

<div class="text-center text-muted py-4">
    No reports uploaded for this phase.
</div>

<?php } ?>

<div class="card border-top border-3 border-primary">
    <div class="card-body">

        <h6 class="fw-semibold mb-3">Admin Action</h6>

        <div class="d-flex justify-content-end gap-2">

            <!-- REJECT -->
            <button class="btn btn-danger"
                    data-bs-toggle="modal"
                    data-bs-target="#rejectModal">
                ❌ Request Correction
            </button>

            <!-- APPROVE -->
<button type="button"
        class="btn btn-success"
        onclick="approvePhase(this)"
        data-phase-id="<?= $phase_id ?>"
        data-project-id="<?= $project_id ?>">
    ✔ Approve Phase
</button>



        </div>

    </div>
</div>


            </div>
            <!-- [ Main Content ] end -->
        </div>
        
        

        <!-- [ Footer ] start -->
        <?php include("footer.php"); ?>
        <!-- [ Footer ] end -->
    </main>

    <div class="modal fade" id="rejectModal" tabindex="-1">
    <div class="modal-dialog modal-lg" role="document">
       

            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Request Correction</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
 <form method="post" action="phase_action.php">
            <input type="hidden" name="action" value="reject">
            <input type="hidden" name="phase_id" value="<?= $phase_id ?>">
            <input type="hidden" name="project_id" value="<?= $project_id ?>">
                <div class="modal-body">
                    <label class="fw-semibold mb-2">
                        Admin Remarks <span class="text-danger">*</span>
                    </label>
                    <textarea name="remark"
                              class="form-control"
                              rows="4"
                              required
                              placeholder="Explain what needs to be corrected..."></textarea>
                </div>

                <div class="modal-footer">
                    <button class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Send Back</button>
                </div>
                </form>
            </div>
        
    </div>
</div>
    <!--! BEGIN: Vendors JS !-->
    <script src="assets/vendors/js/vendors.min.js"></script>
    <!-- vendors.min.js {always must need to be top} -->
    <script src="assets/vendors/js/select2.min.js"></script>
    <script src="assets/vendors/js/select2-active.min.js"></script>
    <script src="assets/vendors/js/datepicker.min.html"></script>
    <script src="assets/vendors/js/lslstrength.min.html"></script>
    <!--! END: Vendors JS !-->
    <!--! BEGIN: Apps Init  !-->
    <script src="assets/js/common-init.min.js"></script>
    <script src="assets/js/customers-create-init.min.js"></script>
    <!--! END: Apps Init !-->
    <!--! BEGIN: Theme Customizer  !-->
    <script src="assets/js/theme-customizer-init.min.js"></script>
    <!--! END: Theme Customizer !-->


<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
function approvePhase(btn){

    // 🔍 SAFETY CHECK
    if(!btn || !btn.dataset.phaseId || !btn.dataset.projectId){
        Swal.fire('Error','Missing phase or project ID','error');
        return;
    }

    const phaseId   = btn.dataset.phaseId;
    const projectId = btn.dataset.projectId;

    // 🟡 CONFIRMATION
    Swal.fire({
        title: 'Approve this phase?',
        text: 'Once approved, next phase will start automatically.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Approve',
        cancelButtonText: 'Cancel'
    }).then((result) => {

        if(result.isConfirmed){

            // ⏳ OPTIONAL LOADING
            Swal.fire({
                title: 'Processing...',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

            // 🚀 AJAX CALL
            fetch('phase_aprove_action.php', {
                method: 'POST',
                headers: {
                    'Content-Type':'application/x-www-form-urlencoded'
                },
                body: `action=approve&phase_id=${encodeURIComponent(phaseId)}&project_id=${encodeURIComponent(projectId)}&ajax=1`
            })
            .then(res => res.text())
            .then(resp => {

                console.log('Server response:', resp);

                if(resp.trim() === 'success'){

                    Swal.fire({
                        icon: 'success',
                        title: 'Approved',
                        text: 'Phase approved successfully',
                        timer: 2000,
                        showConfirmButton: false
                    });

                    // 🔄 STATUS BADGE UPDATE (OPTIONAL)
                    const badge = document.getElementById('phaseStatus');
                    if(badge){
                        badge.className = 'badge bg-soft-success text-success';
                        badge.innerText = 'Approved';
                    }

                } else {

                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: resp || 'Unknown server response'
                    });

                }
            })
            .catch(err => {
                console.error(err);
                Swal.fire('Error','AJAX request failed','error');
            });
        }
    });
}
</script>

<?php if(isset($_GET['reject'])){ ?>
<script>
Swal.fire({
    icon: 'success',
    title: 'Phase Rejected',
    text: 'Phase has been Rejected successfully.'
});
</script>
<?php } ?>
<script>
if (window.location.search.includes('reject=1')) {
    const url = new URL(window.location);
    url.searchParams.delete('reject');
    window.history.replaceState({}, document.title, url.pathname + url.search + window.location.hash);
}
</script>

</body>
</html>
