<?php include 'inc/funtions.php';
if (isset($_SESSION['user_type'])) {
    $user_id = $_SESSION['user_id'];
    $business_id = $_SESSION['business_id'];
    $user = getUserId($user_id);
    $pages_allowed = check_page_access();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard</title>
    
    <link rel="stylesheet" href="assets/css/bootstrap.css">
    
    <link rel="stylesheet" href="assets/vendors/chartjs/Chart.min.css">
    <link rel="stylesheet" href="assets/vendors/simple-datatables/style.css">
    <link rel="stylesheet" href="assets/vendors/perfect-scrollbar/perfect-scrollbar.css">
    <link rel="stylesheet" href="assets/css/app.css">
    <link rel="shortcut icon" href="assets/images/favicon.png" type="image/x-icon">
</head>
<body>
    <div id="app">
        <?php include('inc/header.php'); ?>            
            <div class="main-content container-fluid">
                <div class="mb-4">
                    <h3>Customer Record</h3>
                    <nav aria-label="breadcrumb" class='breadcrumb-header'>
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                            <li class="breadcrumb-item active" aria-current="page">Customer Record</li>
                        </ol>
                    </nav>
                </div> 
                <div class="row g-3 mb-4">
                    <?php
                    // 1. Calculate Total Debtors (Balance < 0)
                    $query_debt = "SELECT COUNT(*) as count, SUM(wallet_balance) as total 
                                   FROM customers 
                                   WHERE wallet_balance < 0 AND business_id = '$business_id'";
                    $res_debt = mysqli_fetch_assoc(Querydb($query_debt));
                    $debt_total = abs($res_debt['total'] ?? 0); // Convert to positive for display
                    $debt_count = $res_debt['count'] ?? 0;

                    // 2. Calculate Total Credits (wallet_balance > 0)
                    $query_credit = "SELECT COUNT(*) as count, SUM(wallet_balance) as total 
                                     FROM customers 
                                     WHERE wallet_balance > 0 AND business_id = '$business_id'";
                    $res_credit = mysqli_fetch_assoc(Querydb($query_credit));
                    $credit_total = $res_credit['total'] ?? 0;
                    $credit_count = $res_credit['count'] ?? 0;

                    // 3. Net Balance
                    $net_balance = $credit_total - $debt_total;
                    $net_color = ($net_balance >= 0) ? 'text-success' : 'text-danger';
                    ?>

                    <div class="col-md-4">
                        <div class="card shadow-sm border-0 border-start border-danger border-4">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h6 class="text-uppercase mb-1 small fw-bold text-muted">Total Debtors</h6>
                                        <h3 class="fw-bold mb-0 text-danger"><?php echo number_format($debt_total); ?></h3>
                                        <small class="text-muted"><?php echo $debt_count; ?> Customers Owe Money</small>
                                    </div>
                                    <div class="bg-danger-soft p-3 rounded-circle">
                                        <i class="bi bi-graph-down-arrow text-danger fs-4"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-4">
                        <div class="card shadow-sm border-0 border-start border-success border-4">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h6 class="text-uppercase mb-1 small fw-bold text-muted">Total Credits</h6>
                                        <h3 class="fw-bold mb-0 text-success"><?php echo number_format($credit_total); ?></h3>
                                        <small class="text-muted"><?php echo $credit_count; ?> Customers with Surplus</small>
                                    </div>
                                    <div class="bg-success-soft p-3 rounded-circle">
                                        <i class="bi bi-graph-up-arrow text-success fs-4"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-4">
                        <div class="card shadow-sm border-0 border-start border-dark border-4">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h6 class="text-uppercase mb-1 small fw-bold text-muted">Net Portfolio Balance</h6>
                                        <h3 class="fw-bold mb-0 <?php echo $net_color; ?>">
                                            <?php echo ($net_balance < 0 ? '-' : '') . number_format(abs($net_balance)); ?>
                                        </h3>
                                        <small class="text-muted">Combined Market Standing</small>
                                    </div>
                                    <div class="bg-dark-soft p-3 rounded-circle">
                                        <i class="bi bi-wallet2 text-dark fs-4"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <section class="section">
                    <div class="row mb-4">
                        <div class="">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h4 class="card-title">Customer Record</h4>
                                </div>
                                <div class="card-body px-0 pb-0">
                                    <div class="table-responsive p-3">
                                        <table class='table table-striped mb-0' id="table1">
                                            <thead>
                                                <tr>
                                                    <th>#</th>
                                                    <th>Name</th>
                                                    <th>Phone</th>
                                                    <th>Email</th>
                                                    <th>Wallet Balance</th>
                                                    <th>Location</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php 
                                                $count = 1;
                                                $all_modals = "";
                                                $role = $_SESSION["role_id"];
                                                $sql = Querydb("SELECT customers.*, user_log.is_active, user_log.id AS log_id, user_log.role_id,
                                                user_log.username as username, user_log.email as user_log_email FROM customers INNER JOIN user_log ON customers.customer_id = user_log.user_id AND user_log.role_id = 5 WHERE customers.business_id = '$business_id' Order BY customer_id desc");
                                                foreach ($sql as $customer) {
                                                 ?>
                                                <tr class="text-center">
                                                    <td><?php echo $count; ?></td>
                                                    <td><?php echo $customer['name']; ?></td>
                                                    <td><?php echo $customer['phone'] ?></td>
                                                    <td><?php echo $customer['email'] ?></td>
                                                    <td class="<?php if($customer['wallet_balance'] >= 0){echo "text-success";}else{echo 'text-danger';} ?>"> ₦ <?php echo number_format($customer['wallet_balance'],2); ?></td>
                                                    <td>
                                                        <?php echo $customer['address']; ?>
                                                    </td>
                                                    <td>
                                                        <div class="btn-group">
                                                            <button type="submit" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#editcustomerModal<?php echo $customer['customer_id']; ?>"><i data-feather="edit"></i> Edit</button>
                                                            <button type="button" class="btn btn-secondary" data-bs-toggle="modal" data-bs-target="#viewcustomerModal<?php echo $customer['customer_id']; ?>"><i data-feather="eye"></i> Preview</button>
                                                            <button type="button" class="btn btn-sm <?php echo ($customer['is_active'] == 1) ? 'btn-warning' : 'btn-success'; ?> customer-toggle-btn" data-logid="<?php echo $customer['log_id']; ?>" data-userid="<?php echo $customer['customer_id']; ?>" data-status="<?php echo $customer['is_active']; ?>">
                                                            <i data-feather="<?php echo ($customer['is_active'] == 1) ? 'user-x' : 'user-check'; ?>"></i> <?php echo ($customer['is_active'] == 1) ? ' Deactive' : ' Active'; ?> 
                                                        </button>
                                                            <button class="btn btn-info" data-bs-toggle="modal" data-bs-target="#history<?php echo $customer['customer_id']; ?>">
                                                                <i data-feather="list"></i> History
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <div class="modal" id="editcustomerModal<?php echo $customer['customer_id']; ?>">
                                                    <div class="modal-dialog modal-dialog-centered">
                                                        <div class="modal-content">
                                                        <div class="modal-header">
                                                            <h4 class="modal-title">Edit Customer</h4>
                                                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                        </div>
                                                        <div class="modal-body">
                                                            <form class="row g-3 needs-validation" novalidate>
                                                                <div class="col-12">
                                                                    <div class="row mt-3 mb-3">
                                                                        <input type="hidden" name="id" id="customer_id_<?php echo $count; ?>" value="<?php echo $customer['customer_id']; ?>">
                                                                        <div class="col-6">
                                                                            <label for="customerName" class="form-label">First Name</label>
                                                                            <input type="text" class="form-control" id="customerName_<?php echo $count; ?>" value="<?php echo $customer['name']; ?>">
                                                                        </div>
                                                                        <div class="col-6">
                                                                            <label for="phonenumber" class="form-label">Phone Number</label>
                                                                            <input type="text" class="form-control" id="phonenumber_<?php echo $count; ?>" value="<?php echo $customer['phone']; ?>">
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                <div class="col-12 mb-3">
                                                                    <label for="customerEmail" class="form-label">Your Email</label>
                                                                    <input type="email" class="form-control" id="customerEmail_<?php echo $count; ?>" value="<?php echo $customer['email']; ?>">
                                                                </div>
                                                                <div class="col-12 mb-3">
                                                                    <label for="address" class="form-label">Your Address</label>
                                                                    <textarea type="text" class="form-control" id="customeraddress_<?php echo $count; ?>"><?php echo $customer['address']; ?></textarea>
                                                                </div>
                                                            </form>
                                                        </div>

                                                        <!-- Modal footer -->
                                                        <div class="modal-footer">
                                                            <button type="button" class="btn bt n-danger" data-bs-dismiss="modal">Close</button>
                                                            <button class="btn btn-primary" type="submit" id="editcustomerModalbtn_<?php echo $count; ?>">Edit Profile</button> 
                                                        </div>

                                                        </div>
                                                    </div>
                                                </div>
                                                <!-- View customer Modal --> 
                                                <div class="modal fade" id="viewcustomerModal<?php echo $customer['customer_id']; ?>" tabindex="-1" aria-hidden="true">
                                                    <div class="modal-dialog modal-dialog-centered modal-md">
                                                        <div class="modal-content">
                                                            <div class="modal-header border-0 pb-0">
                                                                <h5 class="modal-title fw-bold">Customer Profile</h5>
                                                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                            </div>
                                                            
                                                            <div class="modal-body">
                                                                <div class="card bg-light border-0 mb-4">
                                                                    <div class="card-body text-center">
                                                                        <p class="text-muted small mb-1 text-uppercase fw-bold">Current Wallet Balance</p>
                                                                        <h2 class="fw-bold <?php echo ($customer['wallet_balance'] >= 0) ? 'text-success' : 'text-danger'; ?>">
                                                                            ₦ <?php echo number_format($customer['wallet_balance'], 2); ?>
                                                                        </h2>
                                                                        <button type="button" class="btn btn-success px-4 mb-3" 
                                                                                data-bs-toggle="modal" 
                                                                                data-bs-target="#topupModal<?php echo $customer['customer_id']; ?>">
                                                                            <i class="bi bi-plus-circle me-1"></i> Top up
                                                                        </button>
                                                                        <button type="button" class="btn btn-warning px-4 mb-3" 
                                                                                data-bs-toggle="modal" 
                                                                                data-bs-target="#withdrawModal<?php echo $customer['customer_id']; ?>">
                                                                            <i class="bi bi-dash-circle me-1"></i> Withdraw
                                                                        </button>
                                                                    </div>
                                                                </div>

                                                                <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">
                                                                    <li class="nav-item w-50" role="presentation">
                                                                        <button class="nav-link active w-100" data-bs-toggle="pill" data-bs-target="#profile<?php echo $customer['customer_id']; ?>" type="button">Basic Info</button>
                                                                    </li>
                                                                    <li class="nav-item w-50" role="presentation">
                                                                        <button class="nav-link w-100" data-bs-toggle="pill" data-bs-target="#kin<?php echo $customer['customer_id']; ?>" type="button">Next of Kin</button>
                                                                    </li>
                                                                </ul>

                                                                <div class="tab-content">
                                                                    <div class="tab-pane fade show active" id="profile<?php echo $customer['customer_id']; ?>">
                                                                        <div class="list-group list-group-flush">
                                                                            <div class="list-group-item d-flex justify-content-between px-0 py-2 border-0">
                                                                                <span class="text-muted">Full Name</span>
                                                                                <span class="fw-bold"><?php echo $customer['name']; ?></span>
                                                                            </div>
                                                                            <div class="list-group-item d-flex justify-content-between px-0 py-2 border-0">
                                                                                <span class="text-muted">Username</span>
                                                                                <span class="fw-bold"><?php echo $customer['username']; ?></span>
                                                                            </div>
                                                                            <div class="list-group-item d-flex justify-content-between px-0 py-2 border-0">
                                                                                <span class="text-muted">Email</span>
                                                                                <span class="fw-bold"><?php echo $customer['email']; ?></span>
                                                                            </div>
                                                                            <div class="list-group-item d-flex justify-content-between px-0 py-2 border-0">
                                                                                <span class="text-muted">Phone</span>
                                                                                <span class="fw-bold"><?php echo $customer['phone']; ?></span>
                                                                            </div>
                                                                            <div class="list-group-item px-0 py-2 border-0">
                                                                                <span class="text-muted d-block">Address</span>
                                                                                <span class="fw-bold small"><?php echo $customer['address']; ?></span>
                                                                            </div>
                                                                        </div>
                                                                    </div>

                                                                    <div class="tab-pane fade" id="kin<?php echo $customer['customer_id']; ?>">
                                                                        <div class="list-group list-group-flush">
                                                                            <div class="list-group-item d-flex justify-content-between px-0 py-2 border-0">
                                                                                <span class="text-muted">Name</span>
                                                                                <span class="fw-bold"><?php echo $customer['kin_full_name']; ?></span>
                                                                            </div>
                                                                            <div class="list-group-item d-flex justify-content-between px-0 py-2 border-0">
                                                                                <span class="text-muted">Relationship</span>
                                                                                <span class="badge bg-info-light text-info"><?php echo $customer['kin_relation']; ?></span>
                                                                            </div>
                                                                            <div class="list-group-item d-flex justify-content-between px-0 py-2 border-0">
                                                                                <span class="text-muted">Kin Phone</span>
                                                                                <span class="fw-bold"><?php echo $customer['kin_phone_no']; ?></span>
                                                                            </div>
                                                                            <div class="list-group-item px-0 py-2 border-0">
                                                                                <span class="text-muted d-block">Kin Address</span>
                                                                                <span class="fw-bold small"><?php echo $customer['kin_address']; ?></span>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>

                                                            <div class="modal-footer border-0">
                                                                <button class="btn btn-sm btn-outline-warning" data-bs-toggle="modal" data-bs-target="#resendModal" onclick="openResendModal('<?php echo $customer['log_id']; ?>', '<?php echo $customer['user_log_email']; ?>')">
                                                                        <i class="bi bi-envelope-exclamation"></i> Resend Invitation
                                                                    </button>
                                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close Window</button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="modal fade" id="topupModal<?php echo $customer['customer_id']; ?>" tabindex="-1" aria-hidden="true">
                                                    <div class="modal-dialog modal-dialog-centered">
                                                        <div class="modal-content">
                                                            <div class="modal-header text-white">
                                                                <h5 class="modal-title">Top-up Wallet: <?php echo htmlspecialchars($customer['name']); ?></h5>
                                                                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                                                            </div>
                                                            <form id="topupForm<?php echo $customer['customer_id']; ?>">
                                                                <div class="modal-body">
                                                                    <div class="alert alert-secondary text-center">
                                                                        <small class="text-uppercase d-block">Current Balance</small>
                                                                        <h4 id="displayBal<?php echo $customer['customer_id']; ?>">₦ <?php echo number_format($customer['wallet_balance'], 2); ?></h4>
                                                                    </div>

                                                                    <input type="hidden" name="customer_id" value="<?php echo $customer['customer_id']; ?>">
                                                                    
                                                                    <div class="form-group mb-3">
                                                                        <label class="form-label fw-bold">Amount to Add (₦)</label>
                                                                        <input type="number" name="amount" class="form-control form-control-lg" placeholder="0.00" min="1" required>
                                                                    </div>

                                                                    <div class="form-group mb-3">
                                                                        <label class="form-label">Payment Method</label>
                                                                        <select name="payment_method" class="form-select">
                                                                            <option value="Cash">Cash</option>
                                                                            <option value="Transfer">Bank Transfer</option>
                                                                            <option value="POS">POS</option>
                                                                        </select>
                                                                    </div>

                                                                    <div class="form-group">
                                                                        <label class="form-label">Note (Optional)</label>
                                                                        <input type="text" name="description" class="form-control" placeholder="e.g. Deposit">
                                                                    </div>
                                                                </div>
                                                                <div class="modal-footer">
                                                                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                                                                    <button type="button" class="btn btn-success px-4 btn-submit-topup" data-id="<?php echo $customer['customer_id']; ?>">Confirm Top-up</button>
                                                                </div>
                                                            </form>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="modal fade" id="withdrawModal<?php echo $customer['customer_id']; ?>" tabindex="-1" aria-hidden="true">
                                                    <div class="modal-dialog modal-dialog-centered">
                                                        <div class="modal-content">
                                                            <div class="modal-header">
                                                                <h5 class="modal-title text-danger">Withdraw Funds: <?php echo $customer['name']; ?></h5>
                                                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                            </div>
                                                            <form action="" method="POST" id="withdrawForm<?php echo $customer['customer_id']; ?>">
                                                                <div class="modal-body">
                                                                    <input type="hidden" name="customer_id" value="<?php echo $customer['customer_id']; ?>">
                                                                    <input type="hidden" name="type" value="debit">

                                                                    <div class="alert alert-secondary text-center">
                                                                        <small class="text-uppercase d-block">Current Balance</small>
                                                                        <h4 id="displayBal<?php echo $customer['customer_id']; ?>">₦ <?php echo number_format($customer['wallet_balance'], 2); ?></h4>
                                                                    </div>
                                                                    
                                                                    <div class="mb-3">
                                                                        <label class="form-label">Amount to Withdraw (₦)</label>
                                                                        <input type="number" name="amount" class="form-control form-control-lg" placeholder="0.00" required step="10000.00">
                                                                    </div>
                                                                    <div class="mb-3">
                                                                        <label class="form-label">Reason</label>
                                                                        <input type="text" name="note" class="form-control" placeholder="e.g. Service refund">
                                                                    </div>
                                                                </div>
                                                                <div class="modal-footer">
                                                                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                                                                    <button type="submit" class="btn btn-danger btn-submit-withdraw" data-id="<?php echo $customer['customer_id']; ?>">Process Withdrawal</button>
                                                                </div>
                                                            </form>
                                                        </div>
                                                    </div>
                                                </div>
                                                <!-- HISTORY -->
                                                <?php ob_start(); ?>
                                                    <div class="modal fade" id="history<?php echo $customer['customer_id']; ?>" tabindex="-1" aria-hidden="true">
                                                        <div class="modal-dialog modal-xl modal-dialog-scrollable">
                                                            <div class="modal-content">
                                                                <div class="modal-header">
                                                                    <h5 class="modal-title">Transaction History: <?php echo htmlspecialchars($customer['name']); ?></h5>
                                                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                                </div>
                                                                <div class="modal-body">
                                                                    <div class="table-responsive">
                                                                        <table class="table table-hover" id="table1">
                                                                            <thead>
                                                                                <tr>
                                                                                    <th>Description</th>
                                                                                    <th>Date</th>
                                                                                    <th>Amount</th>
                                                                                    <th>Status</th>
                                                                                </tr>
                                                                            </thead>
                                                                            <tbody>
                                                                                <?php
                                                                                $c_id = $customer['customer_id']; 
                                                                                $sql_trans = "SELECT * FROM transactions WHERE customer_id = '$c_id' ORDER BY created_at DESC";
                                                                                $result = Querydb($sql_trans);
                                                                                
                                                                                if ($result->num_rows > 0): 
                                                                                    while($row = $result->fetch_assoc()): 
                                                                                        $is_credit = ($row['type'] == 'credit');
                                                                                        $amount_color = $is_credit ? 'text-success' : 'text-danger';
                                                                                        $prefix = $is_credit ? '+' : '-';
                                                                                ?>
                                                                                    <tr>
                                                                                        <td><?php echo htmlspecialchars($row['description']); ?></td>
                                                                                        <td><?php echo date('M d, Y', strtotime($row['created_at'])); ?></td>
                                                                                        <td class="fw-bold <?php echo $amount_color; ?>">
                                                                                            <?php echo $prefix; ?> ₦ <?php echo number_format(abs($row['amount']), 2); ?>
                                                                                        </td>
                                                                                        <td>
                                                                                            <span class="badge <?php echo ($row['transaction_status'] == 'Successful') ? 'bg-success' : 'bg-warning'; ?>">
                                                                                                <?php echo $row['transaction_status'] ?? 'Successful'; ?>
                                                                                            </span>
                                                                                        </td>
                                                                                    </tr>
                                                                                <?php endwhile; else: ?>
                                                                                    <tr>
                                                                                        <td colspan="4" class="text-center text-muted">No recent transactions.</td>
                                                                                    </tr>
                                                                                <?php endif; ?>
                                                                            </tbody>
                                                                        </table>
                                                                    </div>
                                                                </div>
                                                                <div class="modal-footer">
                                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <?php 
                                                    $all_modals .= ob_get_clean(); 
                                                    $count++;} ?>
                                            </tbody>
                                        </table>
                                        <?php 
                                        // 4. ECHO MODALS AFTER TABLE IS CLOSED
                                        echo $all_modals; 
                                        ?>
                                        <div class="modal fade" id="resendModal" tabindex="-1">
                                          <div class="modal-dialog">
                                            <div class="modal-content">
                                              <div class="modal-header">
                                                <h5 class="modal-title">Resend Invitation</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                              </div>
                                              <div class="modal-body">
                                                <p class="text-muted small">If the email address was incorrect, update it below before resending.</p>
                                                <input type="hidden" id="resend_log_id">
                                                <div class="mb-3">
                                                    <label>Recipient Email</label>
                                                    <input type="email" id="resend_email_input" class="form-control" required>
                                                </div>
                                              </div>
                                              <div class="modal-footer">
                                                <button type="button" class="btn btn-primary btn-resend-action" onclick="executeResend()">Update & Resend Now</button>
                                              </div>
                                            </div>
                                          </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </section>

            </div>
<?php  include('inc/footer.php'); 
} else {
    header('Location: pages-error-404.html');
    exit;
}?>
