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

if (!isset($_GET['phase_id']) || !isset($_GET['project_id'])) {
    die("Invalid Request");
}

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



// ✅ Phase details fetch

$phaseQ = mysqli_query($conn, "
    SELECT phase_name, status ,admin_remark
    FROM project_phases 
    WHERE id = $phase_id AND project_id = $project_id
");

if (mysqli_num_rows($phaseQ) == 0) {
    die("Phase not found");
}

$phase = mysqli_fetch_assoc($phaseQ);

// ===============================
// FETCH PHASE REPORTS (HISTORY)
// ===============================
$reports = mysqli_query($conn, "
    SELECT 
        id,
        report_file,
        remarks,
        created_at
    FROM phase_reports
    WHERE project_id = $project_id
      AND 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 class="page-header-right ms-auto">
                    <div class="page-header-right-items">
                        <div class="d-flex d-md-none">
                            <a href="javascript:void(0)" class="page-header-right-close-toggle">
                                <i class="feather-arrow-left me-2"></i>
                                <span>Back</span>
                            </a>
                        </div>
                        <div class="d-flex align-items-center gap-2 page-header-right-items-wrapper">
                            <a onclick="printPage()" class="btn btn-icon btn-light-brand">
                                <i class="feather-printer"></i>
                            </a>
                       
                        </div>
                    </div>
                    <div class="d-md-none d-flex align-items-center">
                        <a href="javascript:void(0)" class="page-header-right-open-toggle">
                            <i class="feather-align-right fs-20"></i>
                        </a>
                    </div>
                </div>
            </div>
            <!-- [ page-header ] end -->
            <div class="bg-white py-3 border-bottom rounded-0 p-md-0 mb-0">
                <div class="d-md-none d-flex">
                    <a href="javascript:void(0)" class="page-content-left-open-toggle">
                        <i class="feather-align-left fs-20"></i>
                    </a>
                </div>
                
                <div class="d-flex align-items-center justify-content-between">
                    <div class="nav-tabs-wrapper page-content-left-sidebar-wrapper">
                        <div class="d-flex d-md-none">
                            <a href="javascript:void(0)" class="page-content-left-close-toggle">
                                <i class="feather-arrow-left me-2"></i>
                                <span>Back</span>
                            </a>
                        </div>
                        <ul class="nav nav-tabs nav-tabs-custom-style" id="myTab" role="tablist">
                            <li class="nav-item" role="presentation">
                            <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#profileTab">Overview </button>
                            </li>
                          
                         
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" data-bs-toggle="tab" data-bs-target="#notesTab">Discussion</button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" data-bs-toggle="tab" data-bs-target="#commentTab">History</button>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
            <!-- [ Main Content ] start -->
            <div class="main-content">
                <div class="tab-content">

                    <div class="tab-pane fade show active" id="profileTab" role="tabpanel">
                        <div class="card card-body lead-info">
                            <?php if($phase['status'] == 'correction' && !empty($phase['admin_remark'])){ ?>
    <div class="alert alert-danger mb-3">
        <strong>Admin Correction Remark:</strong><br>
        <?= nl2br(htmlspecialchars($phase['admin_remark'])) ?>
    </div>
<?php } ?>

                            <div class="mb-4 d-flex align-items-center justify-content-between">
                            
                            <h5 class="fw-bold mb-1">
                <?php echo $phase['phase_name']; ?>
            </h5>

            
            <span class="badge bg-soft-primary text-primary mb-3 d-inline-block">
                <?php echo ucfirst($phase['status']); ?>
            </span>

            <p class="text-muted mb-0">
                
                This phase is part of the project lifecycle.  
                Please complete the required work and submit the report for admin review.
            </p>

                            </div>
                            
                          
                            </div> 
                        </div>
                   
           
                    <div class="tab-pane fade" id="notesTab" role="tabpanel">
                  <div class="card card-body">
<div class="card">
    <div class="card-body">

        <h6 class="fw-semibold mb-3">
            Discussion – <?= htmlspecialchars($phase['phase_name']); ?>
        </h6>

        <!-- Messages -->
        <div id="chatBox"
             class="border rounded p-2 mb-3"
             style="max-height:350px; overflow-y:auto;">
            Loading...
        </div>

        <!-- Message box -->
        <div class="d-flex gap-2">
            <textarea id="chatMessage"
                      class="form-control"
                      rows="2"
                      placeholder="Type your message..."></textarea>

            <button class="btn btn-primary"
                    onclick="sendMessage()">
                Send
            </button>
        </div>

    </div>
</div>

                    </div>
                    </div>
                    <div class="tab-pane fade" id="commentTab" role="tabpanel">
                        <div class="card card-body">
                    <h6 class="fw-semibold mb-3">Submitted Reports</h6>

<?php if(mysqli_num_rows($reports) > 0){ ?>

<ul class="list-group list-group-flush">

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

    <li class="list-group-item d-flex justify-content-between align-items-start gap-3">

        <!-- LEFT: DATE + REMARKS -->
        <div class="flex-grow-1">
            <div class="fw-semibold">
                <?= date('d M Y, h:i A', strtotime($r['created_at'])) ?>
            </div>

            <?php if(!empty($r['remarks'])){ ?>
                <div class="fs-12 text-muted mt-1">
                    <?= nl2br(htmlspecialchars($r['remarks'])) ?>
                </div>
            <?php } else { ?>
                <div class="fs-12 text-muted mt-1">
                    No remarks provided.
                </div>
            <?php } ?>
        </div>
<?php if($phase['status'] == 'correction'){ ?>
    <div class="alert alert-warning">
        <i class="feather-alert-circle"></i>
        This phase was sent back for correction.
    </div>
<?php } ?>

        <!-- RIGHT: DOWNLOAD -->
        <div class="text-end">
            <a href="../uploads/phase_reports/<?= urlencode($r['report_file']) ?>"
               target="_blank"
               class="btn btn-sm btn-outline-primary">
                <i class="feather-download"></i> &nbsp;Download
            </a>
        </div>

    </li>

<?php } ?>

</ul>

<?php } else { ?>

    <div class="text-center text-muted py-4">
        <i class="feather-file-text fs-20 mb-2 d-block"></i>
        No reports uploaded yet.
    </div>

<?php } ?>


                        </div>
                    </div>
                </div>
            </div>
            <!-- [ Main Content ] end -->
        </div>
        <!-- [ Footer ] start -->
        <?php include("footer.php"); ?>
        <!-- [ Footer ] end -->
    </main>
    <!--! 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>
function printPage() {
    window.print();
}
</script>

<script>
const projectId = <?= $project_id ?>;
const phaseId   = <?= $phase_id ?>;

function fetchMessages(){
    fetch(`ajax_fetch_messages.php?project_id=${projectId}&phase_id=${phaseId}`)
    .then(res => res.text())
    .then(data => {
        const box = document.getElementById('chatBox');
        box.innerHTML = data;
        box.scrollTop = box.scrollHeight;
    });
}

function sendMessage(){
    const msg = document.getElementById('chatMessage').value.trim();
    if(msg==='') return;

    fetch('ajax_send_message.php',{
        method:'POST',
        headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:`project_id=${projectId}&phase_id=${phaseId}&message=${encodeURIComponent(msg)}`
    }).then(()=>{
        document.getElementById('chatMessage').value='';
        fetchMessages();
    });
}
document.getElementById('chatMessage').addEventListener('keydown', function(e){

    // Enter pressed WITHOUT shift → send
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault(); // new line stop
        sendMessage();
    }

    // Shift + Enter → new line allowed
});

fetchMessages();
setInterval(fetchMessages,3000);
</script>


<?php if(isset($_GET['success']) && $_GET['success']==1){ ?>
<script>
Swal.fire({
    icon: 'success',
    title: 'Report Submitted!',
    text: 'Your phase report has been sent to Admin for review.',
    confirmButtonText: 'OK'
});
</script>
<?php } ?>
<script>
if (window.location.search.includes('success=1')) {
    const url = new URL(window.location);
    url.searchParams.delete('success');
    window.history.replaceState({}, document.title, url.pathname + url.search + window.location.hash);
}
</script>
<script>
if(window.location.hash === '#commentTab'){
    let tab = document.querySelector('[data-bs-target="#commentTab"]');
    if(tab){
        new bootstrap.Tab(tab).show();
    }
}
</script>


</body>
</html>
