<div class="container" style="text-align: center;">
  <h3> ACCOUNT DETAILS</h3><hr>
</div>

<div class="container">
  <table class="table table-striped table-bordered table-hover table-responsive">    
      <?php
        $conn = new mysqli($GLOBALS['host'], $GLOBALS['user'], $GLOBALS['pass'], $GLOBALS['db']);
        $conn->set_charset("utf8");
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }

        // Handle agent assignment if submitted
        if (isset($_POST['assign_agent']) && $_SESSION['type'] === 'admin') {
            $ac_no = $_POST['ac_no'];
            $agent_id = $_POST['ac_agent'];
            
            $updateSql = "UPDATE `{$GLOBALS['arif_ac']}` SET AA_AGENT = ? WHERE AA_ACNO = ?";
            $stmt = $conn->prepare($updateSql);
            $stmt->bind_param("ss", $agent_id, $ac_no);
            
            if ($stmt->execute()) {
                echo "<div class='alert alert-success'>Agent assigned successfully!</div>";
            } else {
                echo "<div class='alert alert-danger'>Failed to assign agent: " . $conn->error . "</div>";
            }
            $stmt->close();
        }

        // Handle loan closing
        if (isset($_POST['sp_loan_close_submit']) && !empty($_POST['sp_close_acno'])) {
            $spTargetAcno = $_POST['sp_close_acno'];
            $spNewStatus = 'closed';
            $spClosingDate = date('Y-m-d');

            $spSql = "UPDATE `{$GLOBALS['arif_ac']}` SET STATUS = ?, CLOSING_DATE = ? WHERE AA_ACNO = ?";
            $spStmt = $conn->prepare($spSql);
            if (!$spStmt) {
                die("Prepare failed: " . $conn->error);
            }

            $spStmt->bind_param("sss", $spNewStatus, $spClosingDate, $spTargetAcno);

            if ($spStmt->execute()) {
                echo "<div class='alert alert-success'>Loan A/C <strong>{$spTargetAcno}</strong> closed successfully.</div>";
            } else {
                echo "<div class='alert alert-danger'>Failed to close Loan A/C <strong>{$spTargetAcno}</strong>.</div>";
            }

            $spStmt->close();
        }

        // Handle maturity for recurring accounts
        if (isset($_POST['recurring_maturity_submit']) && !empty($_POST['maturity_acno'])) {
            $maturityAcno = $_POST['maturity_acno'];
            $maturityAction = $_POST['maturity_action'];
            
            if ($maturityAction === 'mature') {
                $maturityDate = date('Y-m-d');
                $maturitySql = "UPDATE `{$GLOBALS['arif_ac']}` SET STATUS = 'matured', CLOSING_DATE = ? WHERE AA_ACNO = ?";
                $maturityStmt = $conn->prepare($maturitySql);
                
                if ($maturityStmt->bind_param("ss", $maturityDate, $maturityAcno) && $maturityStmt->execute()) {
                    echo "<div class='alert alert-success'>Recurring A/C <strong>{$maturityAcno}</strong> marked as matured.</div>";
                } else {
                    echo "<div class='alert alert-danger'>Failed to mark Recurring A/C <strong>{$maturityAcno}</strong> as matured.</div>";
                }
            } elseif ($maturityAction === 'unmature') {
                $unmaturitySql = "UPDATE `{$GLOBALS['arif_ac']}` SET STATUS = NULL, CLOSING_DATE = NULL WHERE AA_ACNO = ?";
                $unmaturityStmt = $conn->prepare($unmaturitySql);
                
                if ($unmaturityStmt->bind_param("s", $maturityAcno) && $unmaturityStmt->execute()) {
                    echo "<div class='alert alert-success'>Recurring A/C <strong>{$maturityAcno}</strong> marked as active again.</div>";
                } else {
                    echo "<div class='alert alert-danger'>Failed to mark Recurring A/C <strong>{$maturityAcno}</strong> as active.</div>";
                }
                $unmaturityStmt->close();
            }
            
            if (isset($maturityStmt)) {
                $maturityStmt->close();
            }
        }

        // Get agent list for dropdown
        $getAgentListsQuery = "SELECT * FROM " . $GLOBALS['arif_users'] . "";
        $agentResult = $conn->query($getAgentListsQuery);
        $agentList = [];
        if ($agentResult && $agentResult->num_rows > 0) {
            while ($row = $agentResult->fetch_assoc()) {
                $agentList[] = $row;
            }
        }

        $sql = "SELECT * FROM `".$GLOBALS['arif_ac']."` WHERE `AA_ACNO`= '".$_GET["no"]."'";
        $result = $conn->query($sql);

        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) { 
                if($row["AA_ACTYPE"]=="D") $AA_ACTYPE="Day";
                if($row["AA_ACTYPE"]=="M") $AA_ACTYPE="Month";
                if($row["AA_ACTYPE"]=="W") $AA_ACTYPE="Week";
                
                if ($row["AA_TYPE"]== "FD") {
                    echo "
                    <tr><th colspan='2'><span class='text-center'>Fixed Deposit A/C of ".$row["AA_NAME"]. "</span></th></tr>
                    <tr>
                        <th>ACCOUNT NO.</th>
                        <td>".$row["AA_ACNO"]. "</td>
                    </tr>
                    <tr>
                        <th>A/C Created</th>
                        <td>".$row["AA_TIMESTAMP"]. "</td>
                    </tr>
                    <tr>
                        <th>EFFECTIVE DATE</th>
                        <td>".$row["AA_DATE"]. "</td>
                    </tr>
                    <tr>
                        <th>ACCOUNT HOLDER</th>
                        <td>".$row["AA_NAME"]. "</td>
                    </tr>
                    <tr>
                        <th>ACCOUNT HOLDER's ID/CARD NO</th>
                        <td>".$row["AA_ICARD_NO"]. "</td>
                    </tr>
                    <tr>
                        <th>EMAIL ID</th>
                        <td>".$row["AA_EMAIL"]. "</td>
                    </tr>
                    <tr>
                        <th>PHONE NO.</th>
                        <td>".$row["AA_PHONE"]. "</td>
                    </tr>
                    <tr>
                        <th>ADDRESS</th>
                        <td>".$row["AA_ADDRESS"]. "</td>
                    </tr>
                    <tr>
                        <th>ACCOUNT TYPE</th>
                        <td>Fixed Deposit</td>
                    </tr>";
                    
                    // Agent row - show current agent or allow assignment
                    echo "<tr>
                            <th>AGENT</th>
                            <td>";
                    if ($_SESSION['type'] === 'admin') {
                        echo "<form method='post' class='form-inline'>
                                <input type='hidden' name='ac_no' value='".$row["AA_ACNO"]."'>
                                <select class='form-control form-control-sm' name='ac_agent'>";
                        
                        if (!empty($row["AA_AGENT"])) {
                            echo "<option value='".$row["AA_AGENT"]."'>Current: ".$row["AA_AGENT"]."</option>";
                        } else {
                            echo "<option value=''>- Select Agent -</option>";
                        }
                        
                        foreach ($agentList as $agent) {
                            echo "<option value='".$agent['user_id']."'>".$agent['user_id']."</option>";
                        }
                        
                        echo "</select>
                              <button type='submit' name='assign_agent' class='btn btn-sm btn-primary ml-2'>Assign</button>
                              </form>";
                    } else {
                        echo !empty($row["AA_AGENT"]) ? $row["AA_AGENT"] : "Not assigned";
                    }
                    echo "</td></tr>";
                    
                    echo "
                    <tr>
                        <th>RATE OF INTEREST</th>
                        <td>".$row["AA_INTEREST"]. "</td>
                    </tr>
                    <tr>
                        <th>AMOUNT PAID</th>
                        <td>".$row["AA_AMOUNT"]. "</td>
                    </tr>
                    <tr>
                        <th>MATURITY DATE</th>
                        <td>".$row["AA_DATE_MATURE"]. "</td>
                    </tr>
                    <tr>
                        <th>NOMINEE DETAILS</th>
                        <td>".$row["AA_NOMINEE_DETAILS"]. "</td>
                    </tr>";
                    
                } elseif ($row["AA_TYPE"]== "Recurring") {
                    $isMatured = $row["STATUS"] === 'matured';
                    
                    echo "
                    <tr>
                        <th style='vertical-align: middle;'>Recurring A/C of ".$row["AA_NAME"]. "</th>
                        <td style='vertical-align: middle; text-align: right;'>
                            <form method='post' style='display: inline;'>
                                <input type='hidden' name='maturity_acno' value='".$row["AA_ACNO"]."'>
                                <input type='hidden' name='maturity_action' value='".($isMatured ? 'unmature' : 'mature')."'>
                                <button type='submit' name='recurring_maturity_submit' class='btn " . ($isMatured ? 'btn-warning' : 'btn-info') . "'>" . ($isMatured ? 'Mark as Active' : 'Mark as Matured') . "</button>
                                " . ($isMatured ? "<br/><span>Matured on: " . date('d-m-Y', strtotime($row["CLOSING_DATE"])) . "</span>" : "") . "
                            </form>
                        </td>
                    </tr>
                    <tr>
                        <th>ACCOUNT NO.</th>
                        <td>".$row["AA_ACNO"]. "</td>
                    </tr>
                    <tr>
                        <th>ACCOUNT TYPE</th>
                        <td>".$row["AA_TYPE"]. "</td>
                    </tr>
                    <tr>
                        <th>PAYMENT TERM</th>
                        <td>".$AA_ACTYPE. "</td>
                    </tr> 
                    <tr>
                        <th>A/C Created</th>
                        <td>".$row["AA_TIMESTAMP"]. "</td>
                    </tr>
                    <tr>
                        <th>EFFECTIVE DATE</th>
                        <td>".$row["AA_DATE"]. "</td>
                    </tr>
                    <tr>
                        <th>ACCOUNT BALANCE</th>
                        <td>".$row["AA_BAL"]. "</td>
                    </tr>
                    <tr>
                        <th>ACCOUNT HOLDER</th>
                        <td>".$row["AA_NAME"]. "</td>
                    </tr>
                    <tr>
                        <th>ID CARD NO</th>
                        <td>".$row["AA_ICARD_NO"]. "</td>
                    </tr>
                    <tr>
                        <th>EMAIL ID</th>
                        <td>".$row["AA_EMAIL"]. "</td>
                    </tr>
                    <tr>
                        <th>PHONE NO.</th>
                        <td>".$row["AA_PHONE"]. "</td>
                    </tr>
                    <tr>
                        <th>ADDRESS</th>
                        <td>".$row["AA_ADDRESS"]. "</td>
                    </tr>";
                    
                    // Agent row - show current agent or allow assignment
                    echo "<tr>
                            <th>AGENT</th>
                            <td>";
                    if ($_SESSION['type'] === 'admin') {
                        echo "<form method='post' class='form-inline'>
                                <input type='hidden' name='ac_no' value='".$row["AA_ACNO"]."'>
                                <select class='form-control form-control-sm' name='ac_agent'>";
                        
                        if (!empty($row["AA_AGENT"])) {
                            echo "<option value='".$row["AA_AGENT"]."'>Current: ".$row["AA_AGENT"]."</option>";
                        } else {
                            echo "<option value=''>- Select Agent -</option>";
                        }
                        
                        foreach ($agentList as $agent) {
                            echo "<option value='".$agent['user_id']."'>".$agent['user_id']."</option>";
                        }
                        
                        echo "</select>
                              <button type='submit' name='assign_agent' class='btn btn-sm btn-primary ml-2'>Assign</button>
                              </form>";
                    } else {
                        echo !empty($row["AA_AGENT"]) ? $row["AA_AGENT"] : "Not assigned";
                    }
                    echo "</td></tr>";
                    
                    echo "
                    <tr>
                        <th>INTEREST</th>
                        <td>".$row["AA_INTEREST"]. "</td>
                    </tr>
                    <tr>
                        <th>INSTALLMENT AMOUNT</th>
                        <td>".$row["AA_INSTALLMENT"]. "</td>
                    </tr>
                    <tr>
                        <th>TOTAL NUMBER OF INSTALLMENTS</th>
                        <td>".$row["AA_NO_OF_PAYMENT"]. "</td>
                    </tr>
                    <tr>
                        <th>NUMBER OF INSTALLMENTS PAID</th>
                        <td>".$row["AA_NO_OF_PAYPAID"]. "</td>
                    </tr>
                    <tr>
                        <th>MATURITY DATE</th>
                        <td>".$row["AA_DATE_MATURE"]. "</td>
                    </tr>
                    <tr>
                        <th>MATURITY AMOUNT</th>
                        <td>".$row["AA_MATURE_VALUE"]. "</td>
                    </tr>
                    <tr>
                        <th>DATE</th>
                        <td>".$row["AA_DATE"]. "</td>
                    </tr>
                    <tr>
                        <th>NOMINEE DETAILS</th>
                        <td>".$row["AA_NOMINEE_DETAILS"]. "</td>
                    </tr>";
                    
                } else {
                    echo "
                    <tr>
                        <th style='vertical-align: middle;'>Loan A/C of {$row["AA_NAME"]}</th>
                        <td style='vertical-align: middle; text-align: right;'>
                            <form method='post' style='display: inline;'>
                                <input type='hidden' name='sp_close_acno' value='{$row["AA_ACNO"]}'>
                                
                                <button type='submit' name='sp_loan_close_submit' class='btn " . ($row["STATUS"] === 'closed' ? 'btn-success' : 'btn-danger') . "'>" . ($row['STATUS'] === 'closed' ? 'Closed' : 'Close this Account') . "</button><br/>
                                
                                " . ($row["STATUS"] === 'closed' ? "<span>" . date('d-m-Y', strtotime($row["CLOSING_DATE"])) . "</span>" : "") . "
                            </form>
                        </td>
                    </tr>
                    
                    <tr>
                        <th>ACCOUNT NO.</th>
                        <td>".$row["AA_ACNO"]. "</td>
                    </tr>
                    <tr>
                        <th>PAYMENT TERM</th>
                        <td>".$AA_ACTYPE. "</td>
                    </tr>
                    <tr>
                        <th>ACCOUNT TYPE</th>
                        <td>".$row["AA_TYPE"]. "</td>
                    </tr>";
                    
                    // Agent row - show current agent or allow assignment
                    echo "<tr>
                            <th>AGENT</th>
                            <td>";
                    if ($_SESSION['type'] === 'admin') {
                        echo "<form method='post' class='form-inline'>
                                <input type='hidden' name='ac_no' value='".$row["AA_ACNO"]."'>
                                <select class='form-control form-control-sm' name='ac_agent'>";
                        
                        if (!empty($row["AA_AGENT"])) {
                            echo "<option value='".$row["AA_AGENT"]."'>Current: ".$row["AA_AGENT"]."</option>";
                        } else {
                            echo "<option value=''>- Select Agent -</option>";
                        }
                        
                        foreach ($agentList as $agent) {
                            echo "<option value='".$agent['user_id']."'>".$agent['user_id']."</option>";
                        }
                        
                        echo "</select>
                              <button type='submit' name='assign_agent' class='btn btn-sm btn-primary ml-2'>Assign</button>
                              </form>";
                    } else {
                        echo !empty($row["AA_AGENT"]) ? $row["AA_AGENT"] : "Not assigned";
                    }
                    echo "</td></tr>";
                    
                    echo "
                    <tr>
                        <th>A/C Created</th>
                        <td>".$row["AA_TIMESTAMP"]. "</td>
                    </tr>
                    <tr>
                        <th>EFFECTIVE DATE</th>
                        <td>".$row["AA_DATE"]. "</td>
                    </tr>
                    <tr>
                        <th>ACCOUNT BALANCE</th>
                        <td>".$row["AA_BAL"]. "</td>
                    </tr>
                    <tr>
                        <th>ACCOUNT HOLDER</th>
                        <td>".$row["AA_NAME"]. "</td>
                    </tr>
                    <tr>
                        <th>ID CARD NO</th>
                        <td>".$row["AA_ICARD_NO"]. "</td>
                    </tr>
                    <tr>
                        <th>EMAIL ID</th>
                        <td>".$row["AA_EMAIL"]. "</td>
                    </tr>
                    <tr>
                        <th>PHONE NO.</th>
                        <td>".$row["AA_PHONE"]. "</td>
                    </tr>
                    <tr>
                        <th>ADDRESS</th>
                        <td>".$row["AA_ADDRESS"]. "</td>
                    </tr>
                    <tr>
                        <th>INTEREST</th>
                        <td>".$row["AA_INTEREST"]. "</td>
                    </tr>
                    <tr>
                        <th>INSTALLMENT AMOUNT</th>
                        <td>".$row["AA_INSTALLMENT"]. "</td>
                    </tr>
                    <tr>
                        <th>LOAN AMOUNT</th>
                        <td>".$row["AA_AMOUNT"]. "</td>
                    </tr>
                    <tr>
                        <th>NUMBER OF PAYMENT</th>
                        <td>".$row["AA_NO_OF_PAYMENT"]. "</td>
                    </tr>
                    <tr>
                        <th>TERM ENDING DATE</th>
                        <td>".$row["AA_DATE_MATURE"]. "</td>
                    </tr>
                    <tr>
                        <th>1st GUARANTER DETAILS</th>
                        <td>".$row["AA_G1_DETAILS"]. "</td>
                    </tr>
                    <tr>
                        <th>2nd GUARANTER DETAILS</th>
                        <td>".$row["AA_G2_DETAILS"]. "</td>
                    </tr>";
                }
            } 
        } else {
            echo "<tr><td colspan='2'>0 results</td></tr>";
        }
        $conn->close();
      ?>
  </table>
</div>