<?php
session_start();
require_once '../config.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    echo "Access Denied";
    exit;
}

function e($v) {
    return htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8');
}

function money($v) {
    return number_format((float)$v, 2, '.', ',');
}

function is_valid_date($d) {
    return is_string($d) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $d);
}

$admin_id = (int)$_SESSION['user_id'];
$msg = $_GET['msg'] ?? '';

/* ============================================================
   APPROVE / MARK AS PAID
============================================================ */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['approve_bill'])) {
    $bill_id = (int)($_POST['bill_id'] ?? 0);

    if ($bill_id > 0) {
        $stmt = $conn->prepare("
           UPDATE bills
SET 
    advance_amount = advance_amount + due_amount,
    due_amount = 0.00,
    payment_status = 'paid',
    due_date = NULL,
    unpaid_due_date = NULL
WHERE id = ?
        ");

        if ($stmt) {
            $stmt->bind_param("i", $bill_id);
            $stmt->execute();
            $affected = $stmt->affected_rows;
            $stmt->close();

            if ($affected > 0) {
                header("Location: unpaid_bills_approval.php?msg=approved");
                exit;
            } else {
                header("Location: unpaid_bills_approval.php?msg=not_found");
                exit;
            }
        }
    }

    header("Location: unpaid_bills_approval.php?msg=invalid");
    exit;
}

/* ============================================================
   FILTERS
============================================================ */
$q      = trim($_GET['q'] ?? '');
$date1  = trim($_GET['date1'] ?? '');
$date2  = trim($_GET['date2'] ?? '');
$range  = trim($_GET['range'] ?? '');

$today = date('Y-m-d');
$monthStart = date('Y-m-01');

if ($range === 'today') {
    $date1 = $today;
    $date2 = $today;
} elseif ($range === 'month') {
    $date1 = $monthStart;
    $date2 = $today;
}

$where = "WHERE b.due_amount > 0";
$params = [];
$types  = "";

if ($q !== '') {
    $where .= " AND (
        CAST(b.id AS CHAR) LIKE ?
        OR b.customer_name LIKE ?
        OR b.customer_gst LIKE ?
        OR b.phone LIKE ?
        OR u.name LIKE ?
    )";
    $like = "%{$q}%";
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $types .= "sssss";
}

if ($date1 !== '' && is_valid_date($date1)) {
    $where .= " AND DATE(b.created_at) >= ?";
    $params[] = $date1;
    $types .= "s";
}

if ($date2 !== '' && is_valid_date($date2)) {
    $where .= " AND DATE(b.created_at) <= ?";
    $params[] = $date2;
    $types .= "s";
}

/* ============================================================
   SUMMARY
============================================================ */
$summarySql = "
    SELECT
        COUNT(*) AS total_unpaid,
        COALESCE(SUM(b.total_amount),0) AS total_amount,
        COALESCE(SUM(b.due_amount),0) AS due_sum
    FROM bills b
    LEFT JOIN users u ON b.created_by = u.id
    {$where}
";
$summaryStmt = $conn->prepare($summarySql);
if ($summaryStmt) {
    if (!empty($params)) {
        $summaryStmt->bind_param($types, ...$params);
    }
    $summaryStmt->execute();
    $summary = $summaryStmt->get_result()->fetch_assoc();
    $summaryStmt->close();
} else {
    $summary = [
        'total_unpaid' => 0,
        'total_amount' => 0,
        'due_sum' => 0,
    ];
}

/* ============================================================
   LIST
============================================================ */
$listSql = "
    SELECT
    b.id,
    b.customer_name,
    b.customer_gst,
    b.phone,
    b.total_amount,
    b.due_amount,
    b.due_date,
    b.unpaid_due_date,
    b.payment_status,
    b.created_at,
    b.created_by,
    u.name AS created_by_name,
u.role AS created_by_role
    FROM bills b
    LEFT JOIN users u ON b.created_by = u.id
    {$where}
    ORDER BY b.created_at DESC, b.id DESC
";

$listStmt = $conn->prepare($listSql);
if (!$listStmt) {
    die("Query prepare failed: " . $conn->error);
}
if (!empty($params)) {
    $listStmt->bind_param($types, ...$params);
}
$listStmt->execute();
$result = $listStmt->get_result();
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Unpaid Bills</title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
    /* ===== BASE ===== */
body{
    background:#eef2f7;
    font-family:'Segoe UI',Arial,sans-serif;
    margin:0;
    color:#0f172a;
}

/* ===== LAYOUT ===== */
.main-content{
    margin-left:270px;
    padding:10px;
}

/* ===== CARD ===== */
.page-card{
    background:#fff;
    border:1px solid rgba(148,163,184,.12);
    border-radius:14px;
    box-shadow:0 6px 18px rgba(15,23,42,.05);
    padding:14px;
}

/* ===== HEADER ===== */
.header-row{
    display:flex;
    justify-content:space-between;
    align-items:flex-start;
    gap:10px;
    flex-wrap:wrap;
    margin-bottom:12px;
}

.page-title{
    display:flex;
    align-items:center;
    gap:8px;
    font-size:22px;
    font-weight:800;
    margin:0;
}

.page-subtitle{
    color:#64748b;
    font-size:12px;
    margin-top:2px;
}

/* ===== BUTTON ===== */
.top-actions{
    display:flex;
    gap:6px;
}

.btn-pill{
    border-radius:10px;
    padding:6px 12px;
    font-weight:600;
    font-size:12px;
    display:inline-flex;
    align-items:center;
    gap:6px;
}

.btn-dark-pill{
    background:#374155;
    color:#fff;
    border:1px solid #374155;
}

.btn-dark-pill:hover{
    background:#1f2937;
}

.btn-light-pill{
    background:#fff;
    color:#334155;
    border:1px solid #d6dde8;
}

/* ===== STATS ===== */
.stat-grid{
    display:grid;
    grid-template-columns:repeat(3,1fr);
    gap:10px;
    margin-bottom:12px;
}

.stat-card{
    background:#fff;
    border:1px solid #e5e7eb;
    border-radius:12px;
    padding:10px;
}

.stat-label{
    color:#64748b;
    font-size:11px;
    font-weight:700;
    text-transform:uppercase;
}

.stat-value{
    font-size:18px;
    font-weight:800;
    margin-top:4px;
}

/* ===== FILTER ===== */
.filter-box{
    background:#f8fafc;
    border:1px solid #e2e8f0;
    border-radius:12px;
    padding:12px;
    margin-bottom:12px;
}

.filter-row{
    display:grid;
    grid-template-columns:2fr 1fr 1fr auto;
    gap:8px;
    align-items:end;
}

.form-label{
    font-size:12px;
    font-weight:600;
    margin-bottom:4px;
}

.form-control,
.form-select{
    padding:6px 10px;
    border-radius:8px;
    border:1px solid #d6dde8;
    font-size:12px;
}

/* ===== TABLE ===== */
.table-wrap{
    overflow-x:auto;
    border-radius:12px;
}

table{
    width:100%;
    border-collapse:collapse;
}

thead th{
    background:#374155;
    color:#fff;
    padding:8px;
    font-size:11px;
    white-space:nowrap;
}

tbody td{
    padding:8px;
    border-bottom:1px solid #eef2f7;
    font-size:12px;
    white-space:nowrap;
}

tbody tr:hover td{
    background:#f4f8ff;
}

/* ===== BADGE ===== */
.badge-soft{
    padding:4px 8px;
    border-radius:999px;
    font-size:10px;
    font-weight:600;
}

.paid{ background:#dcfce7; color:#166534; }
.unpaid{ background:#fee2e2; color:#991b1b; }

/* ===== ACTION ===== */
.actions{
    display:flex;
    gap:6px;
}

.action-btn{
    padding:5px 8px;
    border-radius:8px;
    font-size:11px;
    border:1px solid #d6dde8;
    background:#374155;
    color:#fff;
    cursor:pointer;
}

.action-btn:hover{
    background:#374155;
}

.approve-btn{
    background:#374155;
    border-color:#16a34a;
}

.approve-btn:hover{
    background:#374155;
}

/* ===== EMPTY ===== */
.empty{
    text-align:center;
    padding:20px;
    color:#64748b;
    font-size:13px;
}

/* ===== MOBILE ===== */
@media(max-width:900px){
    .main-content{
        margin-left:0;
        padding:10px;
    }

    .stat-grid{
        grid-template-columns:1fr 1fr;
    }

    .filter-row{
        grid-template-columns:1fr;
    }

    .page-title{
        font-size:20px;
    }
}

@media(max-width:560px){
    .stat-grid{
        grid-template-columns:1fr;
    }
}
</style>
</head>
<body>

<?php include 'adminsidebar.php'; ?>
<?php include '../header.php'; ?>

<div class="main-content">
    <div class="page-card">

        <div class="header-row">
            <div>
                <h1 class="page-title" style="color:#000">
                    <i class="fa-solid fa-circle-exclamation"></i>
                    Unpaid Bills
                </h1>
            </div>

            <div class="top-actions">
                <a href="unpaid_bills_approval.php" class="btn-pill btn-light-pill">
                    <i class="fa-solid fa-rotate-left"></i> Reset
                </a>
            </div>
        </div>

        <?php if ($msg === 'approved'): ?>
            <div class="alert alert-success">successfully pay.</div>
        <?php elseif ($msg === 'not_found'): ?>
            <div class="alert alert-warning">Bill already pay </div>
        <?php elseif ($msg === 'invalid'): ?>
            <div class="alert alert-danger">Invalid request.</div>
        <?php endif; ?>

        <div class="stat-grid">
            <div class="stat-card">
                <div class="stat-label">Total Unpaid Bills</div>
                <div class="stat-value"><?php echo (int)($summary['total_unpaid'] ?? 0); ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Total Amount</div>
                <div class="stat-value">₹<?php echo money($summary['total_amount'] ?? 0); ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Due Amount</div>
                <div class="stat-value">₹<?php echo money($summary['due_sum'] ?? 0); ?></div>
            </div>
        </div>

        <form method="GET" class="filter-box">
            <div class="filter-row">
                <div>
                    <label class="form-label">Search</label>
                    <input type="text" name="q" class="form-control" placeholder="Bill no, customer, phone, GST, created by..." value="<?php echo e($q); ?>">
                </div>
                <div>
                    <label class="form-label">From</label>
                    <input type="date" name="date1" class="form-control" value="<?php echo e($date1); ?>">
                </div>
                <div>
                    <label class="form-label">To</label>
                    <input type="date" name="date2" class="form-control" value="<?php echo e($date2); ?>">
                </div>
                <div class="d-flex gap-2 flex-wrap">
                    <button type="submit" name="range" value="today" class="btn btn-dark btn-pill">
                        <i class="fa-solid fa-calendar-day"></i> Today
                    </button>
                    <button type="submit" name="range" value="month" class="btn btn-outline-secondary btn-pill">
                        <i class="fa-solid fa-calendar-days"></i> This Month
                    </button>
                </div>
            </div>
        </form>

        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
                        <th>Bill No</th>
                        <th>Customer</th>
                        <th>GST / Phone</th>
                        <th>Created By</th>
                        <th>Total</th>
                        <th>Due</th>
                        <th>Due Date</th>
                        <th>Role</th>
                        <th>Status</th>
                        <th>Created At</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                <?php if ($result && $result->num_rows > 0): ?>
                    <?php while ($row = $result->fetch_assoc()): ?>
                      <tr>
    <td><?php echo (int)$row['id']; ?></td>

    <td><?php echo e($row['customer_name'] ?: '-'); ?></td>

    <td>
        <div><?php echo e($row['customer_gst'] ?: '-'); ?></div>
        <div style="color:#64748b;"><?php echo e($row['phone'] ?: '-'); ?></div>
    </td>

    <td><?php echo e($row['created_by_name'] ?: '-'); ?></td>

    <td>₹<?php echo money($row['total_amount']); ?></td>

    <td>₹<?php echo money($row['due_amount']); ?></td>

    <td>
        <?php 
        $date = $row['unpaid_due_date'] ?: $row['due_date'];
        echo !empty($date) ? e(date('d-m-Y', strtotime($date))) : '-'; 
        ?>
    </td>

    <!-- ✅ PANEL -->
    <td>
        <span style="
            padding:5px 10px;
            border-radius:8px;
            font-size:12px;
            font-weight:700;
            background:<?php echo $row['created_by_role']=='sales_manager' ? '#' : '#'; ?>;
        ">
            <?php echo e($row['created_by_role']); ?>
        </span>
    </td>

    <!-- ✅ STATUS -->
    <td>
        <?php if ($row['payment_status'] == 'advance'): ?>
    <span class="badge-soft" style="background:#fff;color:#000;">Pay Later</span>
<?php elseif ($row['payment_status'] == 'paid'): ?>
    <span class="badge-soft paid">paid</span>
<?php else: ?>
    <span class="badge-soft unpaid">unpaid</span>
<?php endif; ?>
    </td>

    <!-- ✅ CREATED AT -->
    <td>
        <?php echo !empty($row['created_at']) ? e(date('d-m-Y h:i A', strtotime($row['created_at']))) : '-'; ?>
    </td>

    <!-- ✅ ACTION -->
    <td>
        <form method="POST" onsubmit="return confirm('Approve this bill as paid?');">
            <input type="hidden" name="bill_id" value="<?php echo (int)$row['id']; ?>">
            <button type="submit" name="approve_bill" class="action-btn approve-btn">
                <i class="fa-solid fa-circle-check"></i>
            </button>
        </form>
    </td>
</tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="10">
                            <div class="empty">No unpaid bills found.</div>
                        </td>
                    </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

    </div>
</div>

</body>
</html>