<div class="container mt-4">
  <div class="card shadow-lg p-4 rounded-3">
    <h4 class="mb-3">Generate Report</h4>
    <form method="get" class="row g-3">
        <div class="col-md-3">
            <label class="form-label">From</label>
            <input value="<?= $_GET['dFrom'] ?? '' ?>" type="date" name="dFrom" class="form-control" required>
        </div>
        <div class="col-md-3">
            <label class="form-label">To</label>
            <input value="<?= $_GET['dTo'] ?? '' ?>" type="date" name="dTo" class="form-control" required>
        </div>

        <?php 
        // ---- if Admin then Agent dropdown and filter with agent----
        if($_SESSION['type'] === 'admin'){ 
            $conn = new mysqli($GLOBALS['host'], $GLOBALS['user'], $GLOBALS['pass'], $GLOBALS['db']);
            if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);
            
            $agents = $conn->query("SELECT * FROM `".$GLOBALS['arif_users']."` WHERE `type`='agent' ORDER BY user_name ASC");
            ?>
            <div class="col-md-3">
                <label class="form-label">Agent</label>
                <select name="agent" id="agent" class="form-control">
                  <option value="">-- All Agents --</option>
                  <?php 
                  if($agents && $agents->num_rows > 0){
                      while($a = $agents->fetch_assoc()){
                          $selected = (isset($_GET['agent']) && $_GET['agent']==$a['user_id']) ? "selected" : "";
                          echo "<option value='".$a['user_id']."' $selected>".$a['user_name']." (".$a['user_id'].")</option>";
                      } 
                  }
                  ?>
                </select>
            </div>
        <?php } ?>

        <div class="col-md-3 d-flex align-items-end" style="margin-top: 25px;">
            <button type="submit" class="btn btn-info w-100" >Generate Report</button>
            <button id="downloadPdf" class="btn btn-danger mt-3"><i class="bi bi-file-earmark-pdf"></i> Download PDF</button>
        </div>
    </form>
  </div>
</div>


<?php
function report_view($type, $dt) {
    $dateFrom = $dt;

    if($type!="month" && $type!="day") {
        $dateFrom = strtotime($dt); 
        $dateFrom = date("Y-m-d", $dateFrom);
        $dateTo = strtotime('+1 day', strtotime($type)); 
        $dateTo = date("Y-m-d", $dateTo);
    } else {
        if($type=="month") {
            $dateFrom = strtotime('-1 day', strtotime($dt)); 
            $dateFrom = date("Y-m-d", $dateFrom);
        }
        $dateTo = strtotime('+1 '.$type, strtotime($dt));
        $dateTo = date("Y-m-d", $dateTo);
    }

    echo '<div class="container mt-4"> 
            <div class="alert alert-primary shadow-sm">
              <h5 class="mb-0">Report Period: '.$dateFrom." → ".$dateTo." (Up to)</h5>
            </div>
          </div>";

    $conn = new mysqli($GLOBALS['host'], $GLOBALS['user'], $GLOBALS['pass'], $GLOBALS['db']);
    if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);

    $totalAmount = 0;
    $rowsData = [];

    echo '
    <div class="container mt-3">
    <div class="card shadow-sm rounded-3">
    <div class="card-body">
    <h5 class="mb-3">Transaction Report</h5>
    <div class="table-responsive">
    <table class="table table-bordered table-hover align-middle" id="reportTable">
      <thead class="table-light">
        <tr>
          <th>Transaction ID</th>
          '.($_SESSION['type'] === 'admin' ? "<th>Agent</th>" : "").'
          <th>Time</th>
          <th>AC No</th>
          <th>Name</th>
          <th>Amount</th>
          '.($_SESSION['type'] === 'admin' ? "<th>Remarks</th>" : "").'
        </tr>
      </thead>
      <tbody>';

    // ----- base query -----
    $sql = "SELECT * FROM `".$GLOBALS['arif_tran']."` INNER JOIN `".$GLOBALS['arif_ac']."` ON `".$GLOBALS['arif_tran']."`.`AT_ACID`=`".$GLOBALS['arif_ac']."`.`AA_ACNO` WHERE `AT_TIMESTAMP` BETWEEN '".$dateFrom." 00:00:00' AND '".$dateTo." 00:00:00'";

    // ----- individual agent report -----
    if($_SESSION['type'] === 'agent') {
        $sql .= " AND `AA_AGENT`='".$_SESSION['user_id']."'";
    }

    // ----- if admin filter option -----
    if($_SESSION['type'] === 'admin' && isset($_GET['agent']) && $_GET['agent']!="") {
        $agentId = $conn->real_escape_string($_GET['agent']);
        $sql .= " AND `AA_AGENT`='".$agentId."'";
    }

    $sql .= " ORDER BY `".$GLOBALS['arif_tran']."`.`AT_ID` DESC";

    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $kolkataTime = date("d M Y, h:i A", strtotime($row["AT_TIMESTAMP"] . " +5 hours 30 minutes"));
            echo "
              <tr>
                <td>".$row["AT_ID"]."</td>    
                ".($_SESSION['type'] === 'admin' ? "<td>".$row["AA_AGENT"]."</td>" : "")."                            
                <td>".$kolkataTime."</td>
                <td>".$row["AT_ACID"]."</td>
                <td>".$row["AA_NAME"]."</td>
                <td>".$row["AT_AMOUNT"]."</td>
                ".($_SESSION['type'] === 'admin' ? "<td style='font-size: 12px;'>".($row["REMARKS"] ?? '')."</td>" : "")."
              </tr>";
            $totalAmount += $row["AT_AMOUNT"];
            $rowsData[] = [$row["AT_ID"], $row["AT_TIMESTAMP"], $row["AT_ACID"], $row["AA_NAME"], $row["AT_AMOUNT"]];
        }
    } else {
        echo "<tr><td colspan='6' class='text-center text-muted'>No results found</td></tr>";
    }
    $conn->close();

    echo '
      </tbody>
    </table>
    </div>
    <hr>
    <h5 class="text-end">Total Transaction Amount : <b>'.$totalAmount.'</b></h5>
    </div>
    </div>
    </div>
    ';

    // pass rows data to JS
    echo "<script>var reportData = ".json_encode($rowsData)."; var totalAmount = ".json_encode($totalAmount).";</script>";
}

// ---- Call report function ----
if(isset($_GET['tday']) && $_GET['tday']!="") report_view('day', $_GET['tday']); 
if(isset($_GET['tmonth']) && $_GET['tmonth']!="") report_view('month', $_GET['tmonth']); 
if(isset($_GET['dFrom']) && $_GET['dTo']!="") report_view($_GET['dTo'], $_GET['dFrom']); 
?>

<!-- PDF Download Scripts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.28/jspdf.plugin.autotable.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const downloadBtn = document.getElementById('downloadPdf');
    if(downloadBtn){
        downloadBtn.addEventListener('click', function() {
            const { jsPDF } = window.jspdf;
            const doc = new jsPDF('p', 'pt', 'a4');

            const userType = "<?php echo $_SESSION['type']; ?>";
            const userName = "<?php echo $_SESSION['name']; ?>";
            const now = new Date();
            const dateTime = now.toLocaleDateString() + " " + now.toLocaleTimeString();
            const titleText = "Grafin Ventures Transaction Report";

            const logo = new Image();
            logo.src = '/asset/images/new_logo2.jpg';
            logo.onload = () => addContent();
            logo.onerror = () => addContent();

            function addContent(){
                try { doc.addImage(logo, 'PNG', 40, 30, 40, 40); } catch(e) {}
                doc.setFontSize(16);
                doc.text(titleText, 100, 50);
                doc.setFontSize(10);
                doc.text(`Generated on: ${dateTime}`, 40, 80);
                doc.text(`User Type: ${userType}`, 40, 95);
                doc.text(`User Name: ${userName}`, 40, 110);

                let y = 130;

                // table
                doc.autoTable({
                    head: [["Txn ID","Time","Account No","Name","Amount"]],
                    body: reportData,
                    startY: y,
                    styles: { fontSize:8, cellPadding:4, lineWidth: 0.1, lineColor:[0,0,0] },
                    headStyles: { fillColor:false, textColor:0 },
                    bodyStyles: { valign:'middle', fillColor:false },
                    alternateRowStyles: { fillColor:false }
                });

                y = doc.lastAutoTable.finalY + 20;
                doc.setFont(undefined,'bold');
                doc.text(`Total Transaction Amount: ${totalAmount}`,40,y);

                // footer
                const pageCount = doc.internal.getNumberOfPages();
                for(let i=1;i<=pageCount;i++){
                    doc.setPage(i);
                    doc.setFontSize(9);
                    doc.text(`Generated by Loan Portal - Confidential`,40,doc.internal.pageSize.height-20);
                    doc.text(`Page ${i} of ${pageCount}`,doc.internal.pageSize.width-60,doc.internal.pageSize.height-20);
                }

                doc.save(`Transaction_Report_${userType}_${userName}_${now.toISOString().slice(0,10)}.pdf`);
            }
        });
    }
});
</script>
