<?php
session_start();
error_reporting(0);

include("check_installation.php");
include("fetch_settings.php");


if(!($_SESSION["adminid"])) {
    header("Location:login.php");
    exit;
}

// --- Handle Delete User ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
    $deleteId = intval($_POST['delete_id']);
    $stmt = $con->prepare("DELETE FROM customers WHERE customerid = ?");
    $stmt->bind_param("i", $deleteId);
    $stmt->execute();
    $stmt->close();
    $deleteSuccess = true;
}

// --- Pagination Logic ---
$limit = 10; // Number of entries per page
$page = isset($_GET['p']) && is_numeric($_GET['p']) ? $_GET['p'] : 1;
$offset = ($page - 1) * $limit;

// Get total number of customers for pagination
$totalStmt = $con->prepare("SELECT COUNT(*) FROM customers");
$totalStmt->execute();
$totalResult = $totalStmt->get_result();
$totalCustomers = $totalResult->fetch_row()[0];
$totalStmt->close();

$totalPages = ceil($totalCustomers / $limit);

// Prepare and execute query with pagination
$custarray = [];
$stmt = $con->prepare("SELECT * FROM customers LIMIT ? OFFSET ?");
$stmt->bind_param("ii", $limit, $offset);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $custarray[] = $row;
}
$stmt->close();

?>
<!DOCTYPE html>
<html lang="en">
<head>
	<title>Dashboard</title>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<meta name="author" content="">
	<meta name="description" content="">


	<link rel="icon" href="../<?= htmlspecialchars($system_favicon); ?>" type="image/<?= pathinfo($system_favicon, PATHINFO_EXTENSION); ?>">

	<link rel="preconnect" href="https://fonts.googleapis.com/">
	<link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin>
	<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&amp;family=Poppins:wght@400;500;700&amp;display=swap">

	<link rel="stylesheet" type="text/css" href="assets/vendor/font-awesome/css/all.min.css">
	<link rel="stylesheet" type="text/css" href="assets/vendor/bootstrap-icons/bootstrap-icons.css">
	<link rel="stylesheet" type="text/css" href="assets/vendor/overlay-scrollbar/css/overlayscrollbars.min.css">
	<link rel="stylesheet" type="text/css" href="assets/vendor/apexcharts/css/apexcharts.css">

	<link rel="stylesheet" type="text/css" href="assets/css/style.css">
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">

    <style>
        .location-cell {
            white-space: pre-line;
        }
        .modal-preformatted {
            white-space: pre-wrap; /* Keeps formatting and wraps text */
        }
        /* Your custom SweetAlert2 styling from the previous response */
        .swal2-popup {
            border-radius: 12px !important; 
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
        }

        .swal2-title {
            color: #333 !important; 
            font-weight: 500 !important;
        }

        .swal2-icon {
            border-color: #4f46e5 !important;
            color: #4f46e5 !important;
        }

        .swal2-confirm {
            background-color: #4f46e5 !important;
            color: #fff !important;
            border: none !important;
            border-radius: 8px !important;
            box-shadow: none !important;
            transition: background-color 0.2s ease;
        }

        .swal2-confirm:focus {
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.5) !important;
        }

        .swal2-confirm:hover {
            background-color: #3e38b3 !important;
        }

        .swal2-cancel {
            background-color: #e2e8f0 !important;
            color: #4a5568 !important;
            border: none !important;
            border-radius: 8px !important;
            box-shadow: none !important;
            transition: background-color 0.2s ease;
        }

        .swal2-cancel:focus {
            box-shadow: 0 0 0 3px rgba(226, 232, 240, 0.5) !important;
        }

        .swal2-cancel:hover {
            background-color: #cbd5e1 !important;
        }
    </style>

</head>

<body>

<main>
	
	<?php include "include/sidebar.php" ?>
	<div class="page-content">
	
		<?php include "include/topbar.php" ?>
		<div class="page-content-wrapper p-xxl-4">
	
			<div class="row">
				<div class="col-12 mb-4 mb-sm-5">
					<div class="d-sm-flex justify-content-between align-items-center">
						<h1 class="h3 mb-2 mb-sm-0">Dashboard</h1>
						<div class="d-grid"><a href="#" class="btn btn-primary-soft mb-0"><i class="bi bi-plus-lg fa-fw"></i> Manage Account</a></div>				
					</div>
				</div>
			</div>

			<div class="row g-4 mb-5">
                <div class="col-12">
                    <div class="card shadow">
                        <div class="card-header border-bottom">
                            <h5 class="card-title mb-0">Customer Accounts</h5>
                        </div>
                        <div class="card-body">
                            <div class="bg-light rounded p-3 d-none d-sm-block">
                                <div class="row row-cols-4 g-4">
                                    <div class="col"><h6 class="mb-0">Customer ID</h6></div>
                                    <div class="col"><h6 class="mb-0">Name</h6></div>
                                    <div class="col"><h6 class="mb-0">Status</h6></div>
                                    <div class="col"><h6 class="mb-0">Action</h6></div>
                                </div>
                            </div>
                            <?php if (!empty($custarray)): ?>
                                <?php foreach ($custarray as $customer): ?>
                                    <div class="row row-cols-1 row-cols-sm-2 row-cols-md-4 g-4 align-items-center border-bottom px-2 py-4">
                                        <div class="col-6">
                                            <small class="d-block d-sm-none">Customer ID:</small>
                                            <h6 class="fw-light mb-0">#<?= htmlspecialchars($customer['customerid']) ?></h6>
                                        </div> 
                                        <div class="col-6">
                                            <small class="d-block d-sm-none">Name:</small>
                                            <h6 class="mb-0 fw-normal"><?= htmlspecialchars($customer['firstname']) ?> <?= htmlspecialchars($customer['lastname']) ?></h6>
                                        </div>
                                        <div class="col-6">
                                            <small class="d-block d-sm-none">Status:</small>
                                            <div class="badge bg-success bg-opacity-10 text-success"><?= htmlspecialchars($customer['accstatus']) ?></div>
                                        </div>
                                        <div class="col-6">
    <small class="d-block d-sm-none">Actions:</small>
    <div class="d-flex gap-1">
        <button type="button" class="btn btn-primary-soft btn-round mb-0 view-btn" 
            data-bs-toggle="modal" 
            data-bs-target="#customerModal" 
            data-customer='<?= json_encode($customer) ?>' title="View Details">
            <i class="fa-regular fa-eye"></i>
        </button>
        <a href="credit.php?custid=<?= urlencode($customer['customerid']) ?>" class="btn btn-success-soft btn-round mb-0" title="Credit">
            <i class="fa-regular fa-credit-card"></i>
        </a>
        <form method="post" onsubmit="return confirmDelete(this);" style="display:inline;">
            <input type="hidden" name="delete_id" value="<?= $customer['customerid']; ?>">
            <button type="submit" class="btn btn-danger-soft btn-round mb-0" title="Delete">
                <i class="fa fa-trash"></i>
            </button>
        </form>
    </div>
</div>

                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="row px-2 py-4 text-center">
                                    <div class="col">
                                        <p class="mb-0">No customer accounts found.</p>
                                    </div>
                                </div>
                            <?php endif; ?>
							
							
                            <div class="card-footer pt-0">
    <div class="d-sm-flex justify-content-sm-between align-items-sm-center">
        <p class="mb-sm-0 text-center text-sm-start">
            Showing <?= min($offset + 1, $totalCustomers); ?> to <?= min($offset + $limit, $totalCustomers); ?> of <?= $totalCustomers; ?> entries
        </p>
        <nav class="mb-sm-0 d-flex justify-content-center" aria-label="navigation">
            <ul class="pagination pagination-sm pagination-primary-soft mb-0">
                <li class="page-item <?= ($page <= 1) ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?p=<?= max(1, $page - 1); ?>">Prev</a>
                </li>
                <?php for ($p = 1; $p <= $totalPages; $p++): ?>
                    <li class="page-item <?= ($p == $page) ? 'active' : ''; ?>">
                        <a class="page-link" href="?p=<?= $p; ?>"><?= $p; ?></a>
                    </li>
                <?php endfor; ?>
                <li class="page-item <?= ($page >= $totalPages) ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?p=<?= min($totalPages, $page + 1); ?>">Next</a>
                </li>
            </ul>
        </nav>
    </div>
</div>
							
							
							
                            <div class="text-end mt-3">
                                <button class="btn btn-secondary" onclick="window.print()">Print Customers' Detail</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
		</div>
		</div>
	<div class="modal fade" id="customerModal" tabindex="-1" aria-labelledby="customerModalLabel" aria-hidden="true">
		<div class="modal-dialog modal-dialog-centered modal-lg">
			<div class="modal-content">
				<div class="modal-header">
					<h5 class="modal-title" id="customerModalLabel">Customer Details</h5>
					<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
				</div>
				<div class="modal-body" id="modal-body-content">
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
				</div>
			</div>
		</div>
	</div>

</main>
<script src="assets/vendor/bootstrap/dist/js/bootstrap.bundle.min.js"></script>

<script src="assets/vendor/overlay-scrollbar/js/overlayscrollbars.min.js"></script>
<script src="assets/vendor/apexcharts/js/apexcharts.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>

<script src="assets/js/functions.js"></script>

<script>
    // confirm delete with SweetAlert
    function confirmDelete(form) {
        event.preventDefault();
        Swal.fire({
            title: 'Are you sure?',
            text: "This will permanently delete the user!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#4f46e5',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete!',
            cancelButtonText: 'No, cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                form.submit();
            }
        });
        return false;
    }
    
    <?php if (isset($deleteSuccess) && $deleteSuccess): ?>
        document.addEventListener('DOMContentLoaded', function() {
            Swal.fire({
                icon: 'success',
                title: 'Deleted!',
                text: 'User has been removed successfully.',
                timer: 2000,
                showConfirmButton: false
            });
        });
    <?php endif; ?>

    // Handle modal content population
    document.addEventListener('DOMContentLoaded', function() {
        var customerModal = document.getElementById('customerModal');
        customerModal.addEventListener('show.bs.modal', function(event) {
            var button = event.relatedTarget;
            var customerData = JSON.parse(button.getAttribute('data-customer'));
            var modalBody = document.getElementById('modal-body-content');
            
            var content = `
                <div class="container-fluid">
                    <div class="row mb-2">
                        <div class="col-sm-4 text-muted"><strong>Customer ID:</strong></div>
                        <div class="col-sm-8">${customerData.customerid}</div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-sm-4 text-muted"><strong>Login ID:</strong></div>
                        <div class="col-sm-8">${customerData.loginid}</div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-sm-4 text-muted"><strong>Name:</strong></div>
                        <div class="col-sm-8">${customerData.firstname} ${customerData.lastname}</div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-sm-4 text-muted"><strong>Email:</strong></div>
                        <div class="col-sm-8">${customerData.email}</div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-sm-4 text-muted"><strong>Status:</strong></div>
                        <div class="col-sm-8">${customerData.accstatus}</div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-sm-4 text-muted"><strong>Location:</strong></div>
                        <div class="col-sm-8">${customerData.city}, ${customerData.state}, ${customerData.country}</div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-sm-4 text-muted"><strong>Account Opening Date:</strong></div>
                        <div class="col-sm-8">${customerData.accopendate}</div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-sm-4 text-muted"><strong>Last Login:</strong></div>
                        <div class="col-sm-8">${customerData.lastlogin}</div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-sm-4 text-muted"><strong>Account Type:</strong></div>
                        <div class="col-sm-8">${customerData.acctype}</div>
                    </div>
                </div>
            `;
            modalBody.innerHTML = content;
        });
    });
</script>

</body>
</html>