<?php
session_start();
include_once('includes/config.php');
if (!isset($_SESSION['uid'])) {
    header('location:logout.php');
    exit();
}

$userId = $_SESSION['uid'];
$userType = $_SESSION['usertype'];

// Handle form submissions
if ($_POST) {
    $action = $_POST['action'];
    $customerId = (int)$_POST['customerId'];
    $transactionType = mysqli_real_escape_string($con, $_POST['transactionType']);
    $amount = (float)$_POST['amount'];
    $paymentMethod = mysqli_real_escape_string($con, $_POST['paymentMethod']);
    $referenceNumber = mysqli_real_escape_string($con, $_POST['referenceNumber']);
    $transactionDate = mysqli_real_escape_string($con, $_POST['transactionDate']);
    $description = mysqli_real_escape_string($con, $_POST['description']);
    $status = mysqli_real_escape_string($con, $_POST['status']);
    
    // Handle file upload
    $voucherImage = '';
    if (!empty($_FILES['voucherImage']['name'])) {
        $targetDir = "uploads/vouchers/";
        if (!file_exists($targetDir)) {
            mkdir($targetDir, 0777, true);
        }
        
        $fileName = time() . '_' . basename($_FILES['voucherImage']['name']);
        $targetFile = $targetDir . $fileName;
        $uploadOk = 1;
        $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
        
        // Check if image file is actual image
        if (isset($_POST["submit"])) {
            $check = getimagesize($_FILES['voucherImage']['tmp_name']);
            if ($check !== false) {
                $uploadOk = 1;
            } else {
                $error = "File is not an image.";
                $uploadOk = 0;
            }
        }
        
        // Check file size (5MB limit)
        if ($_FILES['voucherImage']['size'] > 5000000) {
            $error = "File is too large. Maximum size is 5MB.";
            $uploadOk = 0;
        }
        
        // Allow certain file formats
        if (!in_array($imageFileType, ['jpg', 'jpeg', 'png', 'gif', 'pdf'])) {
            $error = "Only JPG, JPEG, PNG, GIF & PDF files are allowed.";
            $uploadOk = 0;
        }
        
        if ($uploadOk == 1) {
            if (move_uploaded_file($_FILES['voucherImage']['tmp_name'], $targetFile)) {
                $voucherImage = $fileName;
            } else {
                $error = "Error uploading file.";
            }
        }
    }
    
    if (!isset($error)) {
        if ($action == 'create') {
            $insertQuery = "INSERT INTO tblcustomerpayments (CustomerID, TransactionType, Amount, PaymentMethod, ReferenceNumber, TransactionDate, Description, VoucherImage, Status, CreatedBy) 
                           VALUES ($customerId, '$transactionType', $amount, '$paymentMethod', '$referenceNumber', '$transactionDate', '$description', '$voucherImage', '$status', $userId)";
            
            if (mysqli_query($con, $insertQuery)) {
                $success = "Payment record added successfully!";
            } else {
                $error = "Error adding payment record: " . mysqli_error($con);
            }
        } elseif ($action == 'update') {
            $paymentId = (int)$_POST['paymentId'];
            
            // Build update query
            $updateFields = [
                "CustomerID = $customerId",
                "TransactionType = '$transactionType'",
                "Amount = $amount",
                "PaymentMethod = '$paymentMethod'",
                "ReferenceNumber = '$referenceNumber'",
                "TransactionDate = '$transactionDate'",
                "Description = '$description'",
                "Status = '$status'",
                "UpdatedBy = $userId",
                "UpdatedDate = NOW()"
            ];
            
            if (!empty($voucherImage)) {
                $updateFields[] = "VoucherImage = '$voucherImage'";
                
                // Delete old image if exists
                $oldImageQuery = "SELECT VoucherImage FROM tblcustomerpayments WHERE ID = $paymentId";
                $oldImageResult = mysqli_query($con, $oldImageQuery);
                if ($oldImageResult && mysqli_num_rows($oldImageResult) > 0) {
                    $oldImage = mysqli_fetch_assoc($oldImageResult)['VoucherImage'];
                    if (!empty($oldImage) && file_exists("uploads/vouchers/" . $oldImage)) {
                        unlink("uploads/vouchers/" . $oldImage);
                    }
                }
            }
            
            $updateQuery = "UPDATE tblcustomerpayments SET " . implode(', ', $updateFields) . " WHERE ID = $paymentId";
            
            if (mysqli_query($con, $updateQuery)) {
                $success = "Payment record updated successfully!";
            } else {
                $error = "Error updating payment record: " . mysqli_error($con);
            }
        }
    }
}

// Handle delete action
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $paymentId = (int)$_GET['delete'];
    
    // Get image file to delete
    $imageQuery = "SELECT VoucherImage FROM tblcustomerpayments WHERE ID = $paymentId";
    $imageResult = mysqli_query($con, $imageQuery);
    if ($imageResult && mysqli_num_rows($imageResult) > 0) {
        $image = mysqli_fetch_assoc($imageResult)['VoucherImage'];
        if (!empty($image) && file_exists("uploads/vouchers/" . $image)) {
            unlink("uploads/vouchers/" . $image);
        }
    }
    
    $deleteQuery = "UPDATE tblcustomerpayments SET IsActive = 0, UpdatedBy = '$userId', UpdatedDate = NOW() WHERE ID = $paymentId";
    
    if (mysqli_query($con, $deleteQuery)) {
        $success = "Payment record deleted successfully!";
    } else {
        $error = "Error deleting payment record: " . mysqli_error($con);
    }
}

// Get payment for editing
$editPayment = null;
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $paymentId = (int)$_GET['edit'];
    $editQuery = "SELECT * FROM tblcustomerpayments WHERE ID = $paymentId AND IsActive = 1";
    $editResult = mysqli_query($con, $editQuery);
    $editPayment = mysqli_fetch_assoc($editResult);
}

// Fetch payments with pagination and filters
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$recordsPerPage = 15;
$offset = ($page - 1) * $recordsPerPage;

$searchTerm = isset($_GET['search']) ? mysqli_real_escape_string($con, $_GET['search']) : '';
$filterCustomer = isset($_GET['customer']) ? (int)$_GET['customer'] : 0;
$filterType = isset($_GET['type']) ? mysqli_real_escape_string($con, $_GET['type']) : '';
$filterMethod = isset($_GET['method']) ? mysqli_real_escape_string($con, $_GET['method']) : '';
$filterStatus = isset($_GET['status']) ? mysqli_real_escape_string($con, $_GET['status']) : '';
$dateFrom = isset($_GET['date_from']) ? mysqli_real_escape_string($con, $_GET['date_from']) : '';
$dateTo = isset($_GET['date_to']) ? mysqli_real_escape_string($con, $_GET['date_to']) : '';

$whereClause = "WHERE p.IsActive = 1";
if (!empty($searchTerm)) {
    $whereClause .= " AND (c.CustomerName LIKE '%$searchTerm%' OR c.Mobile LIKE '%$searchTerm%' OR p.ReferenceNumber LIKE '%$searchTerm%' OR p.Description LIKE '%$searchTerm%')";
}
if ($filterCustomer > 0) {
    $whereClause .= " AND p.CustomerID = $filterCustomer";
}
if (!empty($filterType)) {
    $whereClause .= " AND p.TransactionType = '$filterType'";
}
if (!empty($filterMethod)) {
    $whereClause .= " AND p.PaymentMethod = '$filterMethod'";
}
if (!empty($filterStatus)) {
    $whereClause .= " AND p.Status = '$filterStatus'";
}
if (!empty($dateFrom)) {
    $whereClause .= " AND p.TransactionDate >= '$dateFrom'";
}
if (!empty($dateTo)) {
    $whereClause .= " AND p.TransactionDate <= '$dateTo'";
}

// Count total records
$countQuery = "SELECT COUNT(*) as total FROM tblcustomerpayments p LEFT JOIN tblcustomers c ON p.CustomerID = c.ID $whereClause";
$countResult = mysqli_query($con, $countQuery);
$totalRecords = mysqli_fetch_assoc($countResult)['total'];
$totalPages = ceil($totalRecords / $recordsPerPage);

// Fetch payments
$paymentsQuery = "SELECT p.*, c.CustomerName, c.Mobile, c.Area, c.CustomerType,
                         u1.FullName as CreatedByName, u2.FullName as UpdatedByName 
                  FROM tblcustomerpayments p 
                  LEFT JOIN tblcustomers c ON p.CustomerID = c.ID
                  LEFT JOIN tblusers u1 ON p.CreatedBy = u1.ID 
                  LEFT JOIN tblusers u2 ON p.UpdatedBy = u2.ID 
                  $whereClause 
                  ORDER BY p.TransactionDate DESC, p.CreatedDate DESC 
                  LIMIT $offset, $recordsPerPage";
$paymentsResult = mysqli_query($con, $paymentsQuery);

// Get statistics
$statsQuery = "SELECT 
    COUNT(*) as TotalTransactions,
    COUNT(CASE WHEN TransactionType = 'Credit' THEN 1 END) as CreditTransactions,
    COUNT(CASE WHEN TransactionType = 'Debit' THEN 1 END) as DebitTransactions,
    COALESCE(SUM(CASE WHEN TransactionType = 'Credit' AND Status = 'Completed' THEN Amount ELSE 0 END), 0) as TotalCredits,
    COALESCE(SUM(CASE WHEN TransactionType = 'Debit' AND Status = 'Completed' THEN Amount ELSE 0 END), 0) as TotalDebits
    FROM tblcustomerpayments WHERE IsActive = 1";
$statsResult = mysqli_query($con, $statsQuery);
$stats = mysqli_fetch_assoc($statsResult);

// Get customers for dropdown (and check for preselected customer)
$customersQuery = "SELECT ID, CustomerName, Mobile FROM tblcustomers WHERE IsActive = 1 ORDER BY CustomerName";
$customersResult = mysqli_query($con, $customersQuery);

// Check if customer is preselected from URL
$preselectedCustomer = isset($_GET['customer']) ? (int)$_GET['customer'] : 0;
$preselectedCustomerData = null;

if ($preselectedCustomer > 0) {
    $preselectedQuery = "SELECT ID, CustomerName, Mobile FROM tblcustomers WHERE ID = $preselectedCustomer AND IsActive = 1";
    $preselectedResult = mysqli_query($con, $preselectedQuery);
    if ($preselectedResult && mysqli_num_rows($preselectedResult) > 0) {
        $preselectedCustomerData = mysqli_fetch_assoc($preselectedResult);
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Customer Payments | Mariyappa Nadar Ricemill</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
    <link href="vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">
    <style>
        .payment-card {
            transition: transform 0.2s, box-shadow 0.2s;
            border-radius: 10px;
            overflow: hidden;
        }
        .payment-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
        }
        .payment-type-credit { 
            border-left: 4px solid #1cc88a; 
            background: linear-gradient(45deg, rgba(28, 200, 138, 0.1), rgba(28, 200, 138, 0.05));
        }
        .payment-type-debit { 
            border-left: 4px solid #e74a3b; 
            background: linear-gradient(45deg, rgba(231, 74, 59, 0.1), rgba(231, 74, 59, 0.05));
        }
        .amount-credit { color: #1cc88a; font-weight: bold; }
        .amount-debit { color: #e74a3b; font-weight: bold; }
        
        /* Customer Search Dropdown Styles */
        #customerDropdown {
            border: 1px solid #d1d3e2;
            border-top: none;
            border-radius: 0 0 0.35rem 0.35rem;
            background: white;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);
        }
        
        #customerDropdown .list-group-item {
            border: none;
            border-bottom: 1px solid #eaecf4;
            cursor: pointer;
            padding: 0.75rem 1rem;
            transition: background-color 0.15s ease-in-out;
        }
        
        #customerDropdown .list-group-item:hover,
        #customerDropdown .list-group-item.active {
            background-color: #f8f9fc;
            color: #5a5c69;
        }
        
        #customerDropdown .list-group-item:last-child {
            border-bottom: none;
        }
        
        .customer-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .customer-name {
            font-weight: 600;
            color: #5a5c69;
        }
        
        .customer-mobile {
            font-size: 0.875rem;
            color: #858796;
        }
        
        .voucher-preview { 
            max-width: 100px; 
            max-height: 60px; 
            cursor: pointer;
            border-radius: 5px;
            border: 1px solid #dee2e6;
        }
        .modal-header { 
            background: linear-gradient(45deg, #4e73df, #36b9cc); 
            color: white; 
        }
        .required { color: red; }
        .form-group { margin-bottom: 0.75rem; }
        .card-body { padding: 1rem; }
        .table td, .table th { padding: 0.5rem; }
        .alert { padding: 0.5rem 1rem; margin-bottom: 0.75rem; }
        .balance-positive { color: #1cc88a; }
        .balance-negative { color: #e74a3b; }
        .balance-zero { color: #6c757d; }
        
        @media (max-width: 768px) {
            .form-group { margin-bottom: 0.5rem; }
            .modal-body { padding: 1rem; }
            .card-body { padding: 0.75rem; }
        }
    </style>
</head>
<body id="page-top">
    <div id="wrapper">
        <?php include_once('includes/sidebar.php');?>
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <?php include_once('includes/topbar.php');?>
                
                <!-- Begin Page Content -->
                <div class="container-fluid">
                    
                    <!-- Page Heading -->
                    <div class="d-sm-flex align-items-center justify-content-between mb-4">
                        <h1 class="h3 mb-0 text-gray-800">
                            <i class="fas fa-money-bill-wave text-primary mr-2"></i>
                            Customer Payments
                        </h1>
                        <div>
                            <a href="customer-reports.php" class="btn btn-info mr-2">
                                <i class="fas fa-chart-bar mr-2"></i>Reports
                            </a>
                            <button class="btn btn-primary" data-toggle="modal" data-target="#paymentModal" onclick="clearForm()">
                                <i class="fas fa-plus mr-2"></i>Add Payment
                            </button>
                        </div>
                    </div>

                    <!-- Alert Messages -->
                    <?php if (isset($success)): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle mr-2"></i><?php echo $success; ?>
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (isset($error)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-circle mr-2"></i><?php echo $error; ?>
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <?php endif; ?>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="card border-left-primary shadow h-100 py-2">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                                Total Transactions</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                                <?php echo number_format($stats['TotalTransactions']); ?>
                                            </div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-receipt fa-2x text-gray-300"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="card border-left-success shadow h-100 py-2">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                                Total Credits</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                                ₹<?php echo number_format($stats['TotalCredits'], 2); ?>
                                            </div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-arrow-up fa-2x text-gray-300"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="card border-left-danger shadow h-100 py-2">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-danger text-uppercase mb-1">
                                                Total Debits</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                                ₹<?php echo number_format($stats['TotalDebits'], 2); ?>
                                            </div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-arrow-down fa-2x text-gray-300"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="card border-left-info shadow h-100 py-2">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                                Net Balance</div>
                                            <div class="h5 mb-0 font-weight-bold <?php 
                                                $netBalance = $stats['TotalCredits'] - $stats['TotalDebits'];
                                                echo $netBalance > 0 ? 'balance-positive' : ($netBalance < 0 ? 'balance-negative' : 'balance-zero');
                                            ?>">
                                                ₹<?php echo number_format($netBalance, 2); ?>
                                            </div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-balance-scale fa-2x text-gray-300"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Search and Filter -->
                    <div class="card shadow mb-3">
                        <div class="card-body py-2">
                            <form method="GET" class="row align-items-end">
                                <div class="col-md-2 mb-2">
                                    <input type="text" class="form-control form-control-sm" name="search" 
                                           placeholder="Search..." value="<?php echo htmlspecialchars($searchTerm); ?>">
                                </div>
                                <div class="col-md-2 mb-2">
                                    <select class="form-control form-control-sm" name="customer">
                                        <option value="">All Customers</option>
                                        <?php while($customer = mysqli_fetch_assoc($customersResult)): ?>
                                        <option value="<?php echo $customer['ID']; ?>" <?php echo $filterCustomer == $customer['ID'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($customer['CustomerName']); ?>
                                        </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                <div class="col-md-1 mb-2">
                                    <select class="form-control form-control-sm" name="type">
                                        <option value="">All Types</option>
                                        <option value="Credit" <?php echo $filterType == 'Credit' ? 'selected' : ''; ?>>Credit</option>
                                        <option value="Debit" <?php echo $filterType == 'Debit' ? 'selected' : ''; ?>>Debit</option>
                                    </select>
                                </div>
                                <div class="col-md-1 mb-2">
                                    <select class="form-control form-control-sm" name="method">
                                        <option value="">All Methods</option>
                                        <option value="Cash" <?php echo $filterMethod == 'Cash' ? 'selected' : ''; ?>>Cash</option>
                                        <option value="Bank Transfer" <?php echo $filterMethod == 'Bank Transfer' ? 'selected' : ''; ?>>Bank Transfer</option>
                                        <option value="Cheque" <?php echo $filterMethod == 'Cheque' ? 'selected' : ''; ?>>Cheque</option>
                                        <option value="UPI" <?php echo $filterMethod == 'UPI' ? 'selected' : ''; ?>>UPI</option>
                                        <option value="Card" <?php echo $filterMethod == 'Card' ? 'selected' : ''; ?>>Card</option>
                                        <option value="Online" <?php echo $filterMethod == 'Online' ? 'selected' : ''; ?>>Online</option>
                                    </select>
                                </div>
                                <div class="col-md-1 mb-2">
                                    <input type="date" class="form-control form-control-sm" name="date_from" 
                                           value="<?php echo $dateFrom; ?>">
                                </div>
                                <div class="col-md-1 mb-2">
                                    <input type="date" class="form-control form-control-sm" name="date_to" 
                                           value="<?php echo $dateTo; ?>">
                                </div>
                                <div class="col-md-4 mb-2">
                                    <div class="btn-group" role="group">
                                        <button type="submit" class="btn btn-primary btn-sm">
                                            <i class="fas fa-search mr-1"></i>Search
                                        </button>
                                        <a href="customer-payments.php" class="btn btn-secondary btn-sm">
                                            <i class="fas fa-times mr-1"></i>Clear
                                        </a>
                                        <button type="button" class="btn btn-success btn-sm" onclick="exportPayments()">
                                            <i class="fas fa-download mr-1"></i>Export
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Payments Table -->
                    <div class="card shadow mb-4">
                        <div class="card-header py-2">
                            <h6 class="m-0 font-weight-bold text-primary">
                                <i class="fas fa-list mr-2"></i>Payment Transactions
                                <span class="text-muted">(<?php echo $totalRecords; ?> total)</span>
                            </h6>
                        </div>
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table class="table table-bordered table-striped table-sm mb-0" width="100%" cellspacing="0">
                                    <thead class="thead-light">
                                        <tr>
                                            <th>#</th>
                                            <th>Date</th>
                                            <th>Customer</th>
                                            <th>Type</th>
                                            <th>Amount</th>
                                            <th>Method</th>
                                            <th>Reference</th>
                                            <th>Status</th>
                                            <th>Voucher</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        $counter = $offset + 1;
                                        while($payment = mysqli_fetch_assoc($paymentsResult)): 
                                        ?>
                                        <tr class="payment-type-<?php echo strtolower($payment['TransactionType']); ?>">
                                            <td><?php echo $counter++; ?></td>
                                            <td>
                                                <strong><?php echo date('M j, Y', strtotime($payment['TransactionDate'])); ?></strong>
                                                <br><small class="text-muted"><?php echo date('h:i A', strtotime($payment['CreatedDate'])); ?></small>
                                            </td>
                                            <td>
                                                <strong><?php echo htmlspecialchars($payment['CustomerName']); ?></strong>
                                                <br><small class="text-muted"><?php echo $payment['Mobile']; ?></small>
                                                <br><small class="text-muted"><?php echo htmlspecialchars($payment['Area']); ?></small>
                                            </td>
                                            <td>
                                                <span class="badge badge-<?php echo $payment['TransactionType'] == 'Credit' ? 'success' : 'danger'; ?> px-2 py-1">
                                                    <i class="fas <?php echo $payment['TransactionType'] == 'Credit' ? 'fa-arrow-up' : 'fa-arrow-down'; ?> mr-1"></i>
                                                    <?php echo $payment['TransactionType']; ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="amount-<?php echo strtolower($payment['TransactionType']); ?>">
                                                    ₹<?php echo number_format($payment['Amount'], 2); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="badge badge-secondary">
                                                    <?php echo $payment['PaymentMethod']; ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php if (!empty($payment['ReferenceNumber'])): ?>
                                                    <code><?php echo htmlspecialchars($payment['ReferenceNumber']); ?></code>
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <span class="badge badge-<?php 
                                                    echo $payment['Status'] == 'Completed' ? 'success' : 
                                                        ($payment['Status'] == 'Pending' ? 'warning' : 'danger'); 
                                                ?>">
                                                    <?php echo $payment['Status']; ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php if (!empty($payment['VoucherImage'])): ?>
                                                    <img src="uploads/vouchers/<?php echo $payment['VoucherImage']; ?>" 
                                                         class="voucher-preview" alt="Voucher"
                                                         onclick="showVoucherModal('uploads/vouchers/<?php echo $payment['VoucherImage']; ?>')">
                                                <?php else: ?>
                                                    <span class="text-muted">No voucher</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <div class="btn-group btn-group-sm" role="group">
                                                    <button class="btn btn-outline-info" 
                                                            onclick="viewPayment(<?php echo $payment['ID']; ?>)"
                                                            title="View Details">
                                                        <i class="fas fa-eye"></i>
                                                    </button>
                                                    <button class="btn btn-outline-primary" 
                                                            onclick="editPayment(<?php echo $payment['ID']; ?>)"
                                                            title="Edit">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <button class="btn btn-outline-danger" 
                                                            onclick="deletePayment(<?php echo $payment['ID']; ?>, '<?php echo htmlspecialchars($payment['CustomerName']); ?>', '<?php echo $payment['TransactionType']; ?>', <?php echo $payment['Amount']; ?>)"
                                                            title="Delete">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endwhile; ?>
                                        
                                        <?php if (mysqli_num_rows($paymentsResult) == 0): ?>
                                        <tr>
                                            <td colspan="10" class="text-center text-muted py-4">
                                                <i class="fas fa-inbox fa-3x mb-3 text-gray-300"></i>
                                                <br>No payment records found
                                            </td>
                                        </tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <!-- Pagination -->
                    <?php if ($totalPages > 1): ?>
                    <nav aria-label="Payment pagination">
                        <ul class="pagination justify-content-center pagination-sm">
                            <?php if ($page > 1): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?php echo $page-1; ?>&search=<?php echo urlencode($searchTerm); ?>&customer=<?php echo $filterCustomer; ?>&type=<?php echo urlencode($filterType); ?>&method=<?php echo urlencode($filterMethod); ?>&status=<?php echo urlencode($filterStatus); ?>&date_from=<?php echo $dateFrom; ?>&date_to=<?php echo $dateTo; ?>">Previous</a>
                            </li>
                            <?php endif; ?>
                            
                            <?php for ($i = max(1, $page-2); $i <= min($totalPages, $page+2); $i++): ?>
                            <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($searchTerm); ?>&customer=<?php echo $filterCustomer; ?>&type=<?php echo urlencode($filterType); ?>&method=<?php echo urlencode($filterMethod); ?>&status=<?php echo urlencode($filterStatus); ?>&date_from=<?php echo $dateFrom; ?>&date_to=<?php echo $dateTo; ?>"><?php echo $i; ?></a>
                            </li>
                            <?php endfor; ?>
                            
                            <?php if ($page < $totalPages): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?php echo $page+1; ?>&search=<?php echo urlencode($searchTerm); ?>&customer=<?php echo $filterCustomer; ?>&type=<?php echo urlencode($filterType); ?>&method=<?php echo urlencode($filterMethod); ?>&status=<?php echo urlencode($filterStatus); ?>&date_from=<?php echo $dateFrom; ?>&date_to=<?php echo $dateTo; ?>">Next</a>
                            </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                    <?php endif; ?>

                </div>
                <!-- /.container-fluid -->
            </div>
            <?php include_once('includes/footer.php');?>
        </div>
    </div>

    <!-- Payment Modal -->
    <div class="modal fade" id="paymentModal" tabindex="-1" role="dialog" aria-labelledby="paymentModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="paymentModalLabel">
                        <i class="fas fa-plus mr-2"></i>Add Payment
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form method="POST" id="paymentForm" enctype="multipart/form-data">
                    <div class="modal-body">
                        <input type="hidden" name="action" id="formAction" value="create">
                        <input type="hidden" name="paymentId" id="paymentId">
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="customerId">Customer <span class="required">*</span></label>
                                    <div class="position-relative">
                                        <input type="text" class="form-control" id="customerSearch" 
                                               placeholder="Type to search customer..." autocomplete="off"
                                               value="<?php echo $preselectedCustomerData ? htmlspecialchars($preselectedCustomerData['CustomerName'] . ' - ' . $preselectedCustomerData['Mobile']) : ''; ?>">
                                        <input type="hidden" id="customerId" name="customerId" required 
                                               value="<?php echo $preselectedCustomerData ? $preselectedCustomerData['ID'] : ''; ?>">
                                        <div id="customerDropdown" class="list-group position-absolute w-100" style="z-index: 1000; max-height: 200px; overflow-y: auto; display: none;"></div>
                                    </div>
                                    <div id="customerBalance" class="mt-1" style="display: none;">
                                        <small class="text-muted">Current Balance: <span id="balanceAmount"></span></small>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="transactionType">Transaction Type <span class="required">*</span></label>
                                    <select class="form-control" id="transactionType" name="transactionType" required>
                                        <option value="">Select Type</option>
                                        <option value="Credit">Credit (Money Received)</option>
                                        <option value="Debit">Debit (Money Paid/Advance)</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="amount">Amount <span class="required">*</span></label>
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text">₹</span>
                                        </div>
                                        <input type="number" class="form-control" id="amount" name="amount" 
                                               step="0.01" min="0" required>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="paymentMethod">Payment Method <span class="required">*</span></label>
                                    <select class="form-control" id="paymentMethod" name="paymentMethod" required>
                                        <option value="Cash">Cash</option>
                                        <option value="Bank Transfer">Bank Transfer</option>
                                        <option value="Cheque">Cheque</option>
                                        <option value="UPI">UPI</option>
                                        <option value="Card">Card</option>
                                        <option value="Online">Online</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="transactionDate">Transaction Date <span class="required">*</span></label>
                                    <input type="date" class="form-control" id="transactionDate" name="transactionDate" 
                                           value="<?php echo date('Y-m-d'); ?>" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="status">Status <span class="required">*</span></label>
                                    <select class="form-control" id="status" name="status" required>
                                        <option value="Completed">Completed</option>
                                        <option value="Pending">Pending</option>
                                        <option value="Cancelled">Cancelled</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="referenceNumber">Reference Number</label>
                            <input type="text" class="form-control" id="referenceNumber" name="referenceNumber" 
                                   placeholder="Cheque number, Transaction ID, etc.">
                        </div>
                        
                        <div class="form-group">
                            <label for="description">Description/Notes <span class="required">*</span></label>
                            <textarea class="form-control" id="description" name="description" rows="3" 
                                      placeholder="Payment details, purpose, etc." required></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label for="voucherImage">Voucher/Receipt Image</label>
                            <input type="file" class="form-control-file" id="voucherImage" name="voucherImage" 
                                   accept="image/*,.pdf">
                            <small class="form-text text-muted">Upload payment voucher, receipt or related document (Max 5MB)</small>
                            <div id="currentVoucher" style="display: none;" class="mt-2">
                                <small class="text-muted">Current voucher: <a href="#" target="_blank" id="currentVoucherLink">View</a></small>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">
                            <i class="fas fa-times mr-1"></i>Cancel
                        </button>
                        <button type="submit" class="btn btn-primary" id="submitBtn">
                            <i class="fas fa-save mr-1"></i>Save Payment
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- View Payment Modal -->
    <div class="modal fade" id="viewPaymentModal" tabindex="-1" role="dialog" aria-labelledby="viewPaymentModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header bg-info text-white">
                    <h5 class="modal-title" id="viewPaymentModalLabel">
                        <i class="fas fa-eye mr-2"></i>Payment Details
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body" id="paymentDetailsContent">
                    <!-- Payment details will be loaded here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Voucher Modal -->
    <div class="modal fade" id="voucherModal" tabindex="-1" role="dialog" aria-labelledby="voucherModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="voucherModalLabel">
                        <i class="fas fa-file-image mr-2"></i>Payment Voucher
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body text-center">
                    <img id="voucherImage" src="" class="img-fluid" style="max-height: 500px;" alt="Voucher">
                </div>
            </div>
        </div>
    </div>

    <?php include_once('includes/footer2.php');?>

    <!-- Bootstrap core JavaScript-->
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
    <script src="js/sb-admin-2.min.js"></script>
    <script src="js/quick-filters.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>

    <script>
        function clearForm() {
            document.getElementById('paymentForm').reset();
            document.getElementById('formAction').value = 'create';
            document.getElementById('paymentId').value = '';
            document.getElementById('customerId').value = '';
            document.getElementById('customerSearch').value = '';
            document.getElementById('paymentModalLabel').innerHTML = '<i class="fas fa-plus mr-2"></i>Add Payment';
            document.getElementById('submitBtn').innerHTML = '<i class="fas fa-save mr-1"></i>Save Payment';
            document.getElementById('customerBalance').style.display = 'none';
            document.getElementById('customerDropdown').style.display = 'none';
            document.getElementById('currentVoucher').style.display = 'none';
            document.getElementById('transactionDate').value = '<?php echo date('Y-m-d'); ?>';
        }

        function updateCustomerBalance() {
            const customerId = document.getElementById('customerId').value;
            if (customerId) {
                fetch('api/get-payment.php?balance=' + customerId)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            const balance = parseFloat(data.balance.Balance);
                            const balanceElement = document.getElementById('balanceAmount');
                            const balanceContainer = document.getElementById('customerBalance');
                            
                            balanceElement.textContent = '₹' + balance.toLocaleString('en-IN', {minimumFractionDigits: 2});
                            balanceElement.className = balance > 0 ? 'balance-positive' : (balance < 0 ? 'balance-negative' : 'balance-zero');
                            balanceContainer.style.display = 'block';
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                    });
            } else {
                document.getElementById('customerBalance').style.display = 'none';
            }
        }

        function editPayment(paymentId) {
            fetch('api/get-payment.php?id=' + paymentId)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const payment = data.payment;
                        document.getElementById('formAction').value = 'update';
                        document.getElementById('paymentId').value = payment.ID;
                        document.getElementById('customerId').value = payment.CustomerID;
                        
                        // Set customer search field
                        document.getElementById('customerSearch').value = payment.CustomerName + ' - ' + payment.Mobile;
                        
                        document.getElementById('transactionType').value = payment.TransactionType;
                        document.getElementById('amount').value = payment.Amount;
                        document.getElementById('paymentMethod').value = payment.PaymentMethod;
                        document.getElementById('referenceNumber').value = payment.ReferenceNumber || '';
                        document.getElementById('transactionDate').value = payment.TransactionDate;
                        document.getElementById('description').value = payment.Description;
                        document.getElementById('status').value = payment.Status;
                        
                        if (payment.VoucherImage) {
                            document.getElementById('currentVoucher').style.display = 'block';
                            document.getElementById('currentVoucherLink').href = 'uploads/vouchers/' + payment.VoucherImage;
                        }
                        
                        updateCustomerBalance();
                        
                        document.getElementById('paymentModalLabel').innerHTML = '<i class="fas fa-edit mr-2"></i>Edit Payment';
                        document.getElementById('submitBtn').innerHTML = '<i class="fas fa-save mr-1"></i>Update Payment';
                        
                        $('#paymentModal').modal('show');
                    } else {
                        alert('Error fetching payment data: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error fetching payment data');
                });
        }

        function viewPayment(paymentId) {
            fetch('api/get-payment.php?id=' + paymentId)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const payment = data.payment;
                        const content = `
                            <div class="row">
                                <div class="col-md-6">
                                    <table class="table table-borderless table-sm">
                                        <tr><td><strong>Customer:</strong></td><td>${payment.CustomerName}</td></tr>
                                        <tr><td><strong>Mobile:</strong></td><td><a href="tel:${payment.Mobile}">${payment.Mobile}</a></td></tr>
                                        <tr><td><strong>Area:</strong></td><td>${payment.Area}</td></tr>
                                        <tr><td><strong>Transaction Type:</strong></td><td>
                                            <span class="badge badge-${payment.TransactionType === 'Credit' ? 'success' : 'danger'} px-2 py-1">
                                                ${payment.TransactionType}
                                            </span>
                                        </td></tr>
                                        <tr><td><strong>Amount:</strong></td><td>
                                            <span class="amount-${payment.TransactionType.toLowerCase()}">₹${parseFloat(payment.Amount).toLocaleString('en-IN', {minimumFractionDigits: 2})}</span>
                                        </td></tr>
                                    </table>
                                </div>
                                <div class="col-md-6">
                                    <table class="table table-borderless table-sm">
                                        <tr><td><strong>Payment Method:</strong></td><td><span class="badge badge-secondary">${payment.PaymentMethod}</span></td></tr>
                                        <tr><td><strong>Transaction Date:</strong></td><td>${new Date(payment.TransactionDate).toLocaleDateString()}</td></tr>
                                        <tr><td><strong>Status:</strong></td><td>
                                            <span class="badge badge-${payment.Status === 'Completed' ? 'success' : (payment.Status === 'Pending' ? 'warning' : 'danger')}">
                                                ${payment.Status}
                                            </span>
                                        </td></tr>
                                        <tr><td><strong>Reference:</strong></td><td>${payment.ReferenceNumber || 'N/A'}</td></tr>
                                        <tr><td><strong>Created By:</strong></td><td>${payment.CreatedByName || 'N/A'}</td></tr>
                                    </table>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-12">
                                    <strong>Description:</strong>
                                    <p class="mt-1 p-2 bg-light border rounded">${payment.Description}</p>
                                </div>
                            </div>
                            ${payment.VoucherImage ? `
                            <div class="row">
                                <div class="col-12">
                                    <strong>Voucher:</strong>
                                    <p class="mt-1">
                                        <button class="btn btn-sm btn-outline-primary" onclick="showVoucherModal('uploads/vouchers/${payment.VoucherImage}')">
                                            <i class="fas fa-file-image mr-1"></i>View Voucher
                                        </button>
                                        <a href="uploads/vouchers/${payment.VoucherImage}" target="_blank" class="btn btn-sm btn-outline-secondary ml-2">
                                            <i class="fas fa-external-link-alt mr-1"></i>Open in New Tab
                                        </a>
                                    </p>
                                </div>
                            </div>
                            ` : ''}
                        `;
                        
                        document.getElementById('paymentDetailsContent').innerHTML = content;
                        $('#viewPaymentModal').modal('show');
                    } else {
                        alert('Error fetching payment data: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error fetching payment data');
                });
        }

        function deletePayment(paymentId, customerName, transactionType, amount) {
            if (confirm(`Are you sure you want to delete this ${transactionType} payment of ₹${amount.toLocaleString('en-IN', {minimumFractionDigits: 2})} for ${customerName}? This action cannot be undone.`)) {
                window.location.href = 'customer-payments.php?delete=' + paymentId;
            }
        }

        function showVoucherModal(imagePath) {
            document.getElementById('voucherImage').src = imagePath;
            $('#voucherModal').modal('show');
        }

        function exportPayments() {
            // Get table data
            const table = document.querySelector('.table');
            const ws = XLSX.utils.table_to_sheet(table);
            
            // Create workbook
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, 'Payments');
            
            // Save file
            const fileName = 'Customer_Payments_Export_' + new Date().toISOString().slice(0, 10) + '.xlsx';
            XLSX.writeFile(wb, fileName);
        }

        // Auto-dismiss alerts after 5 seconds
        setTimeout(function() {
            $('.alert').fadeOut();
        }, 5000);

        // Format amount input
        document.getElementById('amount').addEventListener('input', function(e) {
            let value = e.target.value;
            if (value < 0) {
                e.target.value = '';
            }
        });

        // Customer Search Functionality
        let customerData = [];
        
        // Load customer data when page loads
        document.addEventListener('DOMContentLoaded', function() {
            loadCustomerData();
            
            // If customer is preselected, update balance
            <?php if ($preselectedCustomerData): ?>
            updateCustomerBalance();
            <?php endif; ?>
        });
        
        function loadCustomerData() {
            fetch('api/get-customers-search.php')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        customerData = data.customers;
                    }
                })
                .catch(error => {
                    console.error('Error loading customers:', error);
                });
        }
        
        // Customer search input event
        document.getElementById('customerSearch').addEventListener('input', function(e) {
            const searchTerm = e.target.value.toLowerCase();
            const dropdown = document.getElementById('customerDropdown');
            
            if (searchTerm.length < 2) {
                dropdown.style.display = 'none';
                return;
            }
            
            const filteredCustomers = customerData.filter(customer => 
                customer.CustomerName.toLowerCase().includes(searchTerm) ||
                customer.Mobile.includes(searchTerm)
            );
            
            if (filteredCustomers.length > 0) {
                let html = '';
                filteredCustomers.forEach(customer => {
                    html += `
                        <div class="list-group-item" onclick="selectCustomer(${customer.ID}, '${customer.CustomerName}', '${customer.Mobile}')">
                            <div class="customer-info">
                                <div>
                                    <div class="customer-name">${customer.CustomerName}</div>
                                    <div class="customer-mobile">${customer.Mobile}</div>
                                </div>
                            </div>
                        </div>
                    `;
                });
                dropdown.innerHTML = html;
                dropdown.style.display = 'block';
            } else {
                dropdown.innerHTML = '<div class="list-group-item">No customers found</div>';
                dropdown.style.display = 'block';
            }
        });
        
        // Hide dropdown when clicking outside
        document.addEventListener('click', function(e) {
            const searchInput = document.getElementById('customerSearch');
            const dropdown = document.getElementById('customerDropdown');
            
            if (!searchInput.contains(e.target) && !dropdown.contains(e.target)) {
                dropdown.style.display = 'none';
            }
        });
        
        // Select customer function
        function selectCustomer(customerId, customerName, mobile) {
            document.getElementById('customerId').value = customerId;
            document.getElementById('customerSearch').value = customerName + ' - ' + mobile;
            document.getElementById('customerDropdown').style.display = 'none';
            updateCustomerBalance();
        }
        
        // Clear customer selection when search input is cleared
        document.getElementById('customerSearch').addEventListener('keydown', function(e) {
            if (e.key === 'Backspace' || e.key === 'Delete') {
                if (this.value.length <= 1) {
                    document.getElementById('customerId').value = '';
                    document.getElementById('customerBalance').style.display = 'none';
                }
            }
        });
    </script>

    <?php if ($editPayment): ?>
    <script>
        // Auto-populate form for editing
        $(document).ready(function() {
            editPayment(<?php echo $editPayment['ID']; ?>);
        });
    </script>
    <?php endif; ?>
</body>
</html>
