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

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

$user_id = (int)($_SESSION['user_id']);
$role    = $_SESSION['role'] ?? 'user';

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

if (!function_exists('money')) {
    function money($v) {
        return number_format((float)$v, 2);
    }
}

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

$set_due = isset($_GET['set_due']);
$bill_id  = (int)($_GET['bill_id'] ?? 0);
$today    = date('Y-m-d');

/* ============================================================
   SAVE DUE DATE
============================================================ */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_due'])) {
    $bill_id_post = (int)($_POST['bill_id'] ?? 0);
    $due_date     = trim($_POST['due_date'] ?? '');

    if ($bill_id_post <= 0 || !is_valid_date($due_date)) {
        header("Location: unpaid_sales.php?set_due=1&bill_id=" . $bill_id_post . "&msg=invalid_date");
        exit;
    }

    $today_check = date('Y-m-d');
    if ($due_date < $today_check) {
        header("Location: unpaid_sales.php?set_due=1&bill_id=" . $bill_id_post . "&msg=due_past");
        exit;
    }
if ($role === 'admin') {
    $stmt = $conn->prepare("
        UPDATE bills
        SET unpaid = 1,
            due_date = ?,
            unpaid_due_date = ?,
            payment_status = 'unpaid'
        WHERE id = ?
    ");

    if ($stmt) {
        $stmt->bind_param("ssi", $due_date, $due_date, $bill_id_post);
        $stmt->execute();
        $stmt->close();
    }
} elseif ($role === 'sales_executive') {
    $stmt = $conn->prepare("
        UPDATE bills
        SET unpaid = 1,
            due_date = ?,
            unpaid_due_date = ?,
            payment_status = 'unpaid'
        WHERE id = ? AND created_by = ?
    ");

    if ($stmt) {
        $stmt->bind_param("ssii", $due_date, $due_date, $bill_id_post, $user_id);
        $stmt->execute();
        $stmt->close();
    }
} else {
    $stmt = $conn->prepare("
        UPDATE bills
        SET unpaid = 1,
            due_date = ?,
            unpaid_due_date = ?,
            payment_status = 'unpaid'
        WHERE id = ?
    ");

    if ($stmt) {
        $stmt->bind_param("ssi", $due_date, $due_date, $bill_id_post);
        $stmt->execute();
        $stmt->close();
    }
}

    header("Location: unpaid_sales.php?msg=saved");
    exit;
}

/* ============================================================
   MARK AS UNPAID (if opened from any bill flow)
============================================================ */
if (isset($_GET['type']) && $_GET['type'] === 'unpaid' && !empty($_GET['bill_no'])) {
    $bill_no = (int)$_GET['bill_no'];

    if ($role === 'admin') {
        $stmt = $conn->prepare("
            UPDATE bills
            SET unpaid = 1,
                payment_status = 'unpaid'
            WHERE id = ?
        ");
        if ($stmt) {
            $stmt->bind_param("i", $bill_no);
            $stmt->execute();
            $stmt->close();
        }
    } elseif ($role === 'sales_executive') {
    $stmt = $conn->prepare("
        UPDATE bills
        SET unpaid = 1,
            payment_status = 'unpaid'
        WHERE id = ? AND created_by = ?
    ");
    if ($stmt) {
        $stmt->bind_param("ii", $bill_no, $user_id);
        $stmt->execute();
        $stmt->close();
    }
} else {
    $stmt = $conn->prepare("
        UPDATE bills
        SET unpaid = 1,
            payment_status = 'unpaid'
        WHERE id = ?
    ");
    if ($stmt) {
        $stmt->bind_param("i", $bill_no);
        $stmt->execute();
        $stmt->close();
    }
}

    header("Location: unpaid_sales.php?msg=unpaid");
    exit;
}

/* ============================================================
   MARK AS PAID (ADMIN ONLY)
============================================================ */
if ($role === 'admin' && isset($_GET['paid_id'])) {
    $id = (int)$_GET['paid_id'];

    $stmt = $conn->prepare("
        UPDATE bills
        SET unpaid = 0,
            unpaid_due_date = NULL,
            payment_status = 'paid'
        WHERE id = ?
    ");
    if ($stmt) {
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->close();
    }

    header("Location: unpaid_sales.php?msg=paid");
    exit;
}

/* ============================================================
   SET DUE MODE: FETCH BILL
============================================================ */
$bill = null;
if ($set_due && $bill_id > 0) {
    if ($role === 'admin') {
        $stmt = $conn->prepare("SELECT * FROM bills WHERE id = ?");
        $stmt->bind_param("i", $bill_id);
   } elseif ($role === 'sales_executive') {
    $stmt = $conn->prepare("SELECT * FROM bills WHERE id = ? AND created_by = ?");
    $stmt->bind_param("ii", $bill_id, $user_id);
} else {
    $stmt = $conn->prepare("SELECT * FROM bills WHERE id = ?");
    $stmt->bind_param("i", $bill_id);
}
    $stmt->execute();
    $bill = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$bill) {
        die('Bill not found');
    }
}

/* ============================================================
   LIST MODE FILTERS / QUERY
============================================================ */
$where  = "b.due_amount > 0";
$params = [];
$types  = "";

$from = trim($_GET['from'] ?? '');
$to   = trim($_GET['to'] ?? '');

if ($from !== '' && $to !== '' && is_valid_date($from) && is_valid_date($to)) {
    if ($from > $to) {
        $tmp = $from;
        $from = $to;
        $to   = $tmp;
    }
    $where .= " AND DATE(b.created_at) BETWEEN ? AND ?";
    $params[] = $from;
    $params[] = $to;
    $types   .= "ss";
}

/* ============================
   ROLE BASED FILTER
============================ */

if ($role === 'sales_manager') {

    $where .= " AND (
        b.created_by = ?
        OR b.created_by IN (
            SELECT id FROM users WHERE manager_id = ?
        )
    )";

    $params[] = $user_id;
    $params[] = $user_id;
    $types   .= "ii";
}

elseif ($role === 'sales_executive') {

    $where .= " AND b.created_by = ?";
    $params[] = $user_id;
    $types   .= "i";
}

$sql = "
    SELECT
        b.*,
        u.name AS created_by_name,
        u.role AS created_by_role,
        COALESCE((
            SELECT COUNT(*)
            FROM bill_items bi
            WHERE bi.bill_id = b.id
        ), 0) AS items_count
    FROM bills b
    LEFT JOIN users u ON u.id = b.created_by
    WHERE $where
    ORDER BY b.id DESC
";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    die("Query prepare failed: " . $conn->error);
}

if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}

$stmt->execute();
$result = $stmt->get_result();
$count_rows = $result ? $result->num_rows : 0;
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Unpaid Bills</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"/>

<style>
:root{
    --theme:#334155;
    --theme-dark:#1f2937;
    --bg:#f3f6fb;
    --card:#ffffff;
--ink:#000000;
    --muted:#64748b;
    --stroke:#e5e7eb;
    --soft:#eef4fb;
    --success:#16a34a;
    --danger:#dc2626;
    --warning:#f59e0b;
    --shadow:0 10px 28px rgba(15,23,42,.06);
}
*{box-sizing:border-box}
html,body{
    margin:0;
    padding:0;
    background:var(--bg);
    color:var(--ink);
    font-family:Inter,system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif;
    overflow-x:hidden;
}
body{font-size:14px;}

.container{
    margin-left:260px;
    padding:30px;
    width:calc(100% - 260px);
    overflow:hidden;
}

.page-head{
    display:flex;
    justify-content:space-between;
    align-items:flex-end;
    gap:16px;
    flex-wrap:wrap;
    margin-bottom:16px;
}
.title-wrap{
    display:flex;
    align-items:center;
    gap:12px;
}

/* ICON FIX */
.title-icon{
    width:34px;
    height:34px;
    border-radius:10px;
    display:flex;
    align-items:center;
    justify-content:center;
    font-size:16px;
    background:#eef2ff;
    color:#334155;
}

/* TITLE */
.page-title{
    margin:0;
    font-size:18px;
    font-size:24px;
    font-weight:800;
    line-height:1.2;
}

/* SUBTITLE */
.page-subtitle{
    margin:4px 0 0;
    font-size:12px;
    color:#64748b;
}

.card{
    background:var(--card);
    border:1px solid #edf2f7;
    border-radius:18px;
    box-shadow:var(--shadow);
}

.hero-card{
    padding:18px;
    margin-bottom:16px;
}

.toolbar{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:12px;
    flex-wrap:wrap;
}

.filter-row{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
    align-items:end;
    width:100%;
}

.field{
    display:flex;
    flex-direction:column;
    gap:8px;
    flex:1 1 220px;
    min-width:220px;
}

.field label{
    font-weight:800;
    color:#1e293b;
    font-size:14px;
}

.input{
    width:100%;
    height:40px;
    padding:0 10px;
    border-radius:14px;
    border:1px solid var(--stroke);
    background:#fff;
    outline:none;
    color:var(--ink);
    transition:.2s ease;
    font-size:13px;
}
.input:focus{
    border-color:var(--theme);
    box-shadow:0 0 0 4px rgba(51,65,85,.08);
}

.input[type="search"]{
    min-width:220px;
}

.btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:8px;
    border:none;
    border-radius:14px;
    padding:0 12px;
    height:40px;
    font-size:13px;
    background:var(--theme);
    color:#fff;
    font-weight:800;
    cursor:pointer;
    text-decoration:none;
    transition:.2s ease;
    white-space:nowrap;
    box-shadow:0 8px 18px rgba(51,65,85,.12);
}
.btn:hover{opacity:.95;transform:translateY(-1px)}
.btn.secondary{
    background:#fff;
    color:var(--theme-dark);
    border:1px solid #dbe3ec;
    box-shadow:none;
}
.btn.success{
    background:var(--success);
}
.btn.danger{
    background:var(--danger);
}
.btn.warning{
    background:var(--warning);
    color:#fff;
}

.summary{
    display:flex;
    gap:12px;
    flex-wrap:wrap;
    margin-top:14px;
}
.stat{
    flex:1 1 180px;
    background:linear-gradient(180deg,#fff,#fbfdff);
    border:1px solid #eef2f7;
    border-radius:16px;
    padding:10px;
}
.stat .label{
    color:var(--muted);
    font-weight:700;
    font-size:11px;
    text-transform:uppercase;
    letter-spacing:.08em;
}
.stat .value{
    font-size:18px;
    font-weight:900;
    margin-top:6px;
    color:var(--theme-dark);
}
.top-bar{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:16px;
    flex-wrap:wrap;
}

/* SEARCH */
.search-box{
    flex:1;
    min-width:300px;
    height:54px;
    border-radius:16px;
    padding:0 18px;
    font-size:15px;
}

/* RIGHT SIDE */
.top-actions{
    display:flex;
    align-items:center;
    gap:12px;
    flex-wrap:wrap;
}

/* DARK PILLS */
.pill.dark{
    background:#334155;
    color:#fff;
    border:none;
    font-weight:800;
}

/* EXCEL BUTTON */
.excel-btn{
    height:40px;
    font-size:13px;
  padding:0 12px;
    border-radius:999px;
    border:1px solid #cbd5e1;
    background:#fff;
    color:#334155;
    font-weight:800;
    display:flex;
    align-items:center;
    gap:8px;
    cursor:pointer;
    transition:0.2s;
}

.excel-btn:hover{
    background:#f1f5f9;
}
.pill{
    display:inline-flex;
    align-items:center;
    gap:8px;
    padding:10px 14px;
    border-radius:999px;
    background:var(--soft);
    color:var(--theme);
    font-weight:800;
    border:1px solid #dbe7f5;
    white-space:nowrap;
}

.table-card{
    background:var(--card);
    border:1px solid #edf2f7;
    border-radius:18px;
    box-shadow:var(--shadow);
    overflow:hidden;
    padding:10px;
}

.table-wrap{
    overflow-x:auto;
    padding-bottom:6px;
}

.table-wrap::-webkit-scrollbar{
    height:8px;
}
.table-wrap::-webkit-scrollbar-thumb{
    background:#cbd5e1;
    border-radius:10px;
}
.grid-row .value{
    color:#000 !important;
    font-weight:600;
}
.grid-head,
.grid-row{
    display:grid;
    grid-template-columns:
        95px    /* Date */
        115px   /* Bill */
        150px   /* Created By */
        135px   /* Panel */
        125px   /* Phone */
        minmax(180px, 1.8fr) /* Customer */
        70px    /* Items */
        110px   /* Total */
        110px   /* Paid */
        110px   /* Pending */
        120px   /* Due Date */
        85px;   /* Action */
    gap:12px;
    align-items:center;
    min-width:1520px;
    box-sizing:border-box;
}

.grid-head > div,
.grid-row > div{
    display:flex;
    align-items:center;
    min-width:0;
    white-space:nowrap;
}

.grid-row > div{
    min-height:44;
    font-size: 13px;
}
.grid-row > div:nth-child(7),
.grid-row > div:nth-child(8),
.grid-row > div:nth-child(9),
.grid-row > div:nth-child(10),
.grid-row > div:nth-child(11){
    justify-content:flex-end;
    text-align:right;
}

.grid-head{
    background:var(--theme);
    color:#fff;
    padding:10px 12px;
    font-size:12px;
    font-weight:900;
    letter-spacing:.01em;
    border-radius:14px 14px 0 0;
    margin-bottom:10px;
}

.grid-row{
    padding:10px 0;
    margin:0;
    border-bottom:1px solid #eef2f7;
}


.actions{
    display:flex;
    align-items:center;
    justify-content:center;
    gap:8px;
    flex-wrap:wrap;
}
.grid-row > div,
.grid-head > div{
    justify-content:flex-start;
    padding-right:4px;
}
.grid-row div[data-label="Date"] .value{
    color:#000 !important;
}
.grid-head{
    background:var(--theme);
    color:#fff;
    padding:14px 16px;
    font-weight:900;
    letter-spacing:.01em;
}

.grid-row .value{
    color:#000;
}

.badge{
    color:#000;
    font-weight:700;
}

.pill{
    color:#000;
}
.grid-row{
    padding:14px 0;
    border-bottom:1px solid #eef2f7;
}
.grid-row:last-child{
    border-bottom:none;
    margin-bottom:0;
}
.grid-head > div,
.grid-row > div{
    display:flex;
    align-items:center;
    min-width:0;
    white-space:nowrap;
    box-sizing:border-box;
}

.grid-row > div:nth-child(7),
.grid-row > div:nth-child(8),
.grid-row > div:nth-child(9),
.grid-row > div:nth-child(10),
.grid-row > div:nth-child(11){
    justify-content:flex-end;
    text-align:right;
}

.grid-head > div:nth-child(7),
.grid-head > div:nth-child(8),
.grid-head > div:nth-child(9),
.grid-head > div:nth-child(10),
.grid-head > div:nth-child(11){
    justify-content:flex-end;
    text-align:right;
}
.cell{
    word-break:break-word;
}

.badge{
    display:inline-flex;
    align-items:center;
    padding:4px 8px;
    border-radius:999px;
    font-weight:800;
    font-size:11px;
    background:#fff7ed;
    color:#9a3412;
    border:1px solid #fed7aa;
    line-height:1;
}

.action-btn{
    width:36px;
    height:36px;
    display:flex;
    align-items:center;
    justify-content:center;
    border-radius:12px;
    background:#f1f5f9;   /* light grey */
    border:1px solid #e2e8f0;
    color:#334155;        /* icon color */
    text-decoration:none;
    transition:all 0.2s ease;
}

.action-btn i{
    font-size:14px;
}

.action-btn:hover{
    background:#e2e8f0;
    transform:translateY(-1px);
}
.icon-btn.paid{
    background:var(--success);
    color:#fff;
    border-color:var(--success);
}

.small-form{
    display:flex;
    gap:8px;
    flex-wrap:wrap;
    align-items:center;
}
.small-form .input{
    min-width:150px;
    height:44px;
    border-radius:12px;
    padding:0 12px;
}

.empty{
    margin:16px;
    padding:22px;
    text-align:center;
    color:var(--muted);
    background:#fafcff;
    border:1px dashed #dbe3ec;
    border-radius:14px;
    font-weight:700;
}

.toast{
    position:fixed;
    right:20px;
    bottom:20px;
    background:#111827;
    color:#fff;
    padding:12px 16px;
    border-radius:12px;
    font-weight:700;
    display:none;
    z-index:9999;
    box-shadow:0 12px 30px rgba(0,0,0,.18);
}

.form-shell{
    max-width:980px;
    margin:0 auto;
}

.form-card{
    padding:22px;
}

.form-header{
    display:flex;
    justify-content:space-between;
    gap:16px;
    align-items:flex-start;
    flex-wrap:wrap;
    margin-bottom:18px;
}

.form-title{
    margin:0;
    font-size:26px;
    font-weight:900;
    color:var(--theme-dark);
}
.form-desc{
    margin:6px 0 0;
    color:var(--muted);
    font-size:14px;
}

.bill-meta{
    display:grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap:12px;
    margin-bottom:18px;
}
.meta-box{
    border:1px solid #e8eef6;
    background:#fbfdff;
    border-radius:16px;
    padding:14px;
}
.meta-label{
    display:block;
    font-size:12px;
    text-transform:uppercase;
    letter-spacing:.08em;
    color:var(--muted);
    font-weight:800;
    margin-bottom:8px;
}
.meta-value{
    font-size:16px;
    font-weight:800;
    color:var(--theme-dark);
    word-break:break-word;
}

.due-grid{
    display:grid;
    grid-template-columns: 1fr 1fr;
    gap:16px;
    margin-top:8px;
}

.control{
    display:flex;
    flex-direction:column;
    gap:8px;
}

.control label{
    font-weight:800;
    color:#1e293b;
    font-size:14px;
}

.actions-row{
    margin-top:20px;
    display:flex;
    gap:10px;
    justify-content:flex-end;
    flex-wrap:wrap;
}

.notice,
.bad{
    border-radius:12px;
    padding:12px 14px;
    margin-bottom:14px;
    font-weight:700;
}
.notice{
    color:#065f46;
    background:#ecfdf5;
    border:1px solid #a7f3d0;
}
.bad{
    color:#991b1b;
    background:#fef2f2;
    border:1px solid #fecaca;
}

/* ================= RESPONSIVE FIX ================= */

/* TABLET */
@media (max-width: 1100px) {
    .container{
        margin-left:0 !important;
        width:100% !important;
        padding:16px !important;
    }

    .page-head{
        flex-direction:column;
        align-items:flex-start;
        gap:10px;
    }

    .title-wrap{
        align-items:flex-start;
        gap:10px;
    }

    .title-icon{
        width:40px;
        height:40px;
        font-size:18px;
        flex:0 0 auto;
    }

    .page-title{
        font-size:22px;
        line-height:1.2;
    }

    .page-subtitle{
        font-size:12px;
    }

    .hero-card,
    .form-card{
        padding:14px !important;
    }

    .toolbar,
    .top-bar{
        flex-direction:column;
        align-items:stretch;
        gap:10px;
    }

    .filter-row{
        flex-direction:column;
        align-items:stretch;
        gap:10px;
    }

    .field{
        min-width:0 !important;
        flex:1 1 100%;
        width:100%;
    }

    .input,
    .input[type="search"]{
        width:100%;
        min-width:0 !important;
    }

    .top-actions{
        width:100%;
        flex-direction:column;
        align-items:stretch;
        gap:8px;
    }

    .pill,
    .excel-btn{
        width:100%;
        justify-content:center;
    }

    .btn{
        width:100%;
    }

    .bill-meta{
        grid-template-columns:1fr;
    }

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

    .actions-row{
        justify-content:stretch;
    }

    .actions-row .btn,
    .actions-row a{
        width:100%;
    }

    .grid-head{
        display:none;
    }

    .table-card{
        padding:8px;
    }

    .grid-row{
        display:block;
        background:#fff;
        border:1px solid #edf2f7;
        border-radius:16px;
        padding:12px;
        margin:12px 0 0;
        min-width:0 !important;
    }

    .grid-row > div{
        display:flex;
        justify-content:space-between;
        gap:14px;
        padding:9px 0;
        border-bottom:1px dashed #eef2f7;
        white-space:normal;
        min-width:0;
    }

    .grid-row > div:last-child{
        border-bottom:none;
    }

    .grid-row > div::before{
        content:attr(data-label);
        font-weight:800;
        color:var(--muted);
        flex:0 0 42%;
        max-width:42%;
        white-space:normal;
    }

    .grid-row > div > .value{
        flex:1;
        text-align:right;
        white-space:normal;
        word-break:break-word;
    }

    .actions{
        justify-content:flex-end;
    }

    .small-form{
        justify-content:flex-end;
    }
}

/* MOBILE */
@media (max-width: 768px) {
    .container{
        margin-left:0 !important;
        width:100% !important;
        padding:12px !important;
    }

    .page-head{
        margin-bottom:12px;
    }

    .title-wrap{
        flex-direction:row;
        align-items:flex-start;
        gap:8px;
    }

    .title-icon{
        width:36px;
        height:36px;
        font-size:16px;
    }

    .page-title{
        font-size:18px !important;
        line-height:1.25;
    }

    .page-subtitle{
        font-size:11px;
        margin-top:4px;
    }

    .card,
    .hero-card,
    .form-card{
        border-radius:14px;
    }

    .hero-card,
    .form-card{
        padding:12px !important;
    }

    .filter-row{
        gap:8px;
    }

    .field{
        gap:4px;
    }

    .field label{
        font-size:12px;
    }

    .input{
        height:40px;
        font-size:13px;
        border-radius:10px;
    }

    .btn{
        height:42px;
        font-size:13px;
        border-radius:12px;
    }

    .top-actions{
        gap:8px;
    }

    .pill{
        font-size:12px;
        padding:8px 12px;
    }

    .excel-btn{
        height:42px;
        font-size:13px;
        padding:0 14px;
        border-radius:12px;
    }

    .summary{
        gap:8px;
        margin-top:10px;
    }

    .stat{
        flex:1 1 100%;
        padding:12px;
        border-radius:14px;
    }

    .stat .value{
        font-size:18px;
    }

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

    .form-desc{
        font-size:13px;
    }

    .meta-box{
        padding:12px;
        border-radius:14px;
    }

    .meta-value{
        font-size:14px;
    }

    .due-grid{
        grid-template-columns:1fr;
        gap:12px;
    }

    .control{
        gap:6px;
    }

    .control label{
        font-size:13px;
    }

    .actions-row{
        margin-top:16px;
        gap:8px;
        flex-direction:column;
        align-items:stretch;
    }

    .actions-row .btn,
    .actions-row a{
        width:100%;
    }

    .grid-row{
        padding:12px;
        border-radius:14px;
    }

    .grid-row > div{
        padding:8px 0;
        gap:10px;
        font-size:13px;
    }

    .grid-row > div::before{
        flex:0 0 40%;
        max-width:40%;
        font-size:12px;
    }

    .badge{
        font-size:10px;
        padding:4px 7px;
    }

    .action-btn{
        width:34px;
        height:34px;
        border-radius:10px;
    }

    .action-btn i{
        font-size:14px;
    }

    .empty{
        margin:10px;
        padding:16px;
        font-size:13px;
    }

    .toast{
        right:12px;
        bottom:12px;
        left:12px;
        width:auto;
        text-align:center;
        font-size:13px;
    }
}
</style>
</head>
<body>

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

<div class="container">

<?php
$msg = $_GET['msg'] ?? '';
if ($msg === 'saved'): ?>
<?php elseif ($msg === 'paid'): ?>
<?php elseif ($msg === 'unpaid'): ?>
<?php elseif ($msg === 'due_past'): ?>
<?php elseif ($msg === 'invalid_date'): ?>
<?php endif; ?>

<?php if ($set_due && $bill): ?>

    <?php
        $from_date = !empty($bill['created_at']) ? date('Y-m-d', strtotime($bill['created_at'])) : $today;
        $due_date  = !empty($bill['unpaid_due_date']) ? date('Y-m-d', strtotime($bill['unpaid_due_date'])) : $today;
        $bill_no   = 'BILL-' . (int)$bill['id'];
        $cust_name = trim((string)($bill['customer_name'] ?? '')) ?: '—';
        $phone     = trim((string)($bill['phone'] ?? '')) ?: '—';
        $total_amt = isset($bill['total_amount']) ? money($bill['total_amount']) : '0.00';
    ?>

    <div class="form-shell">
        <div class="page-head">
            <div>
                <h1 class="page-title">Unpaid Bills</h1>
                <p class="page-subtitle">Set the unpaid start date and payment due date for this bill.</p>
            </div>
            <div class="pill">
                <i class="fa-solid fa-receipt"></i> Bill #<?php echo (int)$bill['id']; ?>
            </div>
        </div>

        <div class="card form-card">
            <div class="form-header">
                <div>
                    <h2 class="form-title">Unpaid Finalize</h2>
                    <p class="form-desc">Please confirm the unpaid period and due date.</p>
                </div>
            </div>

            <div class="bill-meta">
                <div class="meta-box">
                    <span class="meta-label">Bill No.</span>
                    <div class="meta-value"><?php echo e($bill_no); ?></div>
                </div>
                <div class="meta-box">
                    <span class="meta-label">Customer</span>
                    <div class="meta-value"><?php echo e($cust_name); ?></div>
                </div>
                <div class="meta-box">
                    <span class="meta-label">Phone</span>
                    <div class="meta-value"><?php echo e($phone); ?></div>
                </div>
                <div class="meta-box">
                    <span class="meta-label">Total Amount</span>
                    <div class="meta-value">₹ <?php echo e($total_amt); ?></div>
                </div>
                <div class="meta-box">
                    <span class="meta-label">Current Date</span>
                    <div class="meta-value"><?php echo e(date('d-m-Y')); ?></div>
                </div>
                <div class="meta-box">
                    <span class="meta-label">Status</span>
                    <div class="meta-value">Pending / Unpaid</div>
                </div>
            </div>

            <form method="POST">
                <input type="hidden" name="bill_id" value="<?php echo (int)$bill_id; ?>">

                <div class="due-grid">
                    <div class="control">
                        <label>Unpaid From</label>
                        <input type="date" class="input" value="<?php echo e($from_date); ?>" readonly>
                    </div>

                    <div class="control">
                        <label>Payment Due Date</label>
                        <input type="date" name="due_date" class="input" min="<?php echo e($today); ?>" value="<?php echo e($due_date); ?>" required>
                    </div>
                </div>

                <div class="actions-row">
                    <a href="unpaid_sales.php" class="btn secondary">
                        <i class="fa-solid fa-xmark"></i> Cancel
                    </a>
                    <button type="submit" name="save_due" class="btn">
                        <i class="fa-solid fa-floppy-disk"></i> Save
                    </button>
                </div>
            </form>
        </div>
    </div>

<?php else: ?>

   <div class="page-head">
    <div class="title-wrap">
        <span class="title-icon">
            <i class="fa-solid fa-file-invoice-dollar"></i>
        </span>

        <div>
            <h1 class="page-title" style="color: #000;">Unpaid Bills</h1>
            <p class="page-subtitle">Monitor unpaid billing cycles & manage pending payments.</p>
        </div>
    </div>
</div>

    <div class="hero-card card">
        <form method="GET" class="toolbar">
            <div class="filter-row">
                <div class="field">
                    <label>From</label>
                    <input type="date" name="from" class="input" value="<?php echo e($_GET['from'] ?? ''); ?>">
                </div>

                <div class="field">
                    <label>To</label>
                    <input type="date" name="to" class="input" value="<?php echo e($_GET['to'] ?? ''); ?>">
                </div>

                <div style="display:flex; gap:10px; align-items:flex-end; flex-wrap:wrap;">
                    <button type="button" class="btn secondary" onclick="setToday()">
                        Today
                    </button>
                    <button type="button" class="btn secondary" onclick="setThisMonth()">
                        This Month
                    </button>
                    <button class="btn" type="submit">
                        <i class="fa-solid fa-magnifying-glass"></i> Search
                    </button>
                </div>
            </div>
        </form>

        <div class="summary">
            
          
        </div>
    </div>

    <div class="hero-card card" style="padding:14px 18px;">
       <div class="toolbar top-bar">

    <!-- LEFT SEARCH -->
    <input type="search" id="search" class="input search-box"
           placeholder="Search Bill No, Customer, Products">

    <!-- RIGHT SIDE -->
    <div class="top-actions">
        
        <div class="pill dark">All Time</div>

        <div class="pill dark" id="count">
            <?php echo (int)$count_rows; ?> bills
        </div>

        <button type="button" id="excelBtn" class="excel-btn">
            <i class="fa-solid fa-file-excel"></i> Export in Excel
        </button>

    </div>
</div>

    <div class="table-card">
        <div class="table-wrap">
            <div class="grid-head">
                  <div>Date</div>
    <div>Bill</div>
    <div>Created By</div>
    <div>Panel</div>
    <div>Phone</div>
    <div>Customer</div>
                <div>Items</div>
                <div>Total</div>
                <div>Paid</div>
                <div>Pending</div>
                <div>Due Date</div>
                <div>Action</div>
            </div>

            <div id="list">
                <?php if ($result && $result->num_rows > 0): ?>
                    <?php while ($r = $result->fetch_assoc()): ?>
                        <?php
                            $billId  = (int)$r['id'];
                            $created = !empty($r['created_at']) ? date('Y-m-d', strtotime($r['created_at'])) : '—';
                            $billNo  = 'BILL-' . $billId;
                            $phone   = $r['phone'] ?? '';
                            $cust    = $r['customer_name'] ?? '';
                            $items   = (int)($r['items_count'] ?? 0);
                            $total   = isset($r['total_amount']) ? money($r['total_amount']) : '0.00';
                            $paid    = isset($r['advance_amount']) ? money($r['advance_amount']) : '0.00';
                            $pending = isset($r['due_amount']) ? money($r['due_amount']) : '0.00';
                           $dueRaw = !empty($r['unpaid_due_date']) ? $r['unpaid_due_date'] : ($r['due_date'] ?? '');

if (!empty($dueRaw) && $dueRaw !== '0000-00-00') {
    $dueDate = date('Y-m-d', strtotime($dueRaw));
} else {
    $dueDate = '';
}
                        ?>
                        <div class="grid-row data">
    <div data-label="Date"><span class="value"><?php echo e($created); ?></span></div>
    <div data-label="Bill"><span class="value badge"><?php echo e($billNo); ?></span></div>

    <div data-label="Created By">
        <span class="value"><?php echo e($r['created_by_name'] ?? 'N/A'); ?></span>
    </div>

    <div data-label="Panel">
        <span class="value badge"><?php echo e($r['created_by_role'] ?? 'N/A'); ?></span>
    </div>

    <div data-label="Phone"><span class="value"><?php echo e($phone ?: '—'); ?></span></div>
    <div data-label="Customer"><span class="value"><?php echo e($cust ?: '—'); ?></span></div>
    <div data-label="Items"><span class="value"><?php echo e($items); ?></span></div>
    <div data-label="Total"><span class="value">₹<?php echo e($total); ?></span></div>

    <div data-label="Paid">
        <span class="value" style="color:green;">₹<?php echo e($paid); ?></span>
    </div>

    <div data-label="Pending">
        <span class="value" style="color:red;">₹<?php echo e($pending); ?></span>
    </div>

    <div data-label="Due Date">
        <span class="value">
            <?php echo $dueDate ? e(date('d-m-Y', strtotime($dueDate))) : '—'; ?>
        </span>
    </div>

    <div data-label="Action">
        <span class="value actions">
            <a href="invoice_view.php?id=<?php echo $billId; ?>" class="action-btn" title="Invoice">
                <i class="fa-regular fa-file-lines"></i>
            </a>

            <?php if ($role === 'admin'): ?>
                <a href="?paid_id=<?php echo $billId; ?>" class="icon-btn paid" title="Mark Paid" onclick="return confirm('Mark this bill as paid?');">
                    <i class="fa-solid fa-check"></i>
                </a>
            <?php endif; ?>
        </span>
    </div>
</div>
                    <?php endwhile; ?>
                <?php else: ?>
                    <div class="empty">No unpaid bills found</div>
                <?php endif; ?>
            </div>
        </div>
    </div>

<?php endif; ?>

</div>

<div class="toast" id="toast"></div>

<script>
function setToday() {
    const today = new Date().toISOString().split('T')[0];
    const from = document.querySelector("input[name='from']");
    const to = document.querySelector("input[name='to']");
    if (from) from.value = today;
    if (to) to.value = today;
}

function setThisMonth() {
    const now = new Date();
    const first = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0];
    const last  = new Date(now.getFullYear(), now.getMonth() + 1, 0).toISOString().split('T')[0];
    const from = document.querySelector("input[name='from']");
    const to = document.querySelector("input[name='to']");
    if (from) from.value = first;
    if (to) to.value = last;
}

document.addEventListener('DOMContentLoaded', function () {
    const input = document.getElementById('search');
    const rows  = Array.from(document.querySelectorAll('.data'));
    const count = document.getElementById('count');

    if (input && rows.length) {
        function update() {
            const q = (input.value || '').toLowerCase().trim();
            let visible = 0;

            rows.forEach(row => {
                const text = row.innerText.toLowerCase();
                const show = text.includes(q);
                row.style.display = show ? '' : 'none';
                if (show) visible++;
            });

            if (count) {
                count.textContent = visible + (visible === 1 ? ' bill' : ' bills');
            }
        }

        input.addEventListener('input', update);
        update();
    }

    const t = document.getElementById('toast');
    const map = {
        paid: 'Marked Paid',
        saved: 'Saved',
        due_past: 'Due date cannot be earlier than today.',
        invalid_date: 'Invalid date provided.',
        unpaid: 'Marked Unpaid'
    };

    if (msg && t && map[msg]) {
        t.textContent = map[msg];
        t.style.display = 'block';
        setTimeout(() => { t.style.display = 'none'; }, 3000);
    }
});


function downloadExcelFromTable() {

    const rows = Array.from(document.querySelectorAll('.grid-row.data'))
        .filter(row => row.style.display !== 'none');

    // Fixed headers (clean)
    const headers = [
        "Date",
        "Bill",
        "Created By",
        "Panel",
        "Phone",
        "Customer",
        "Items",
        "Total",
        "Paid",
        "Pending",
        "Due Date"
    ];

    let csv = headers.join(",") + "\n";

    rows.forEach(row => {

        const cells = row.querySelectorAll(':scope > div');

        const rowData = [
            cells[0]?.innerText.trim() || '',
            cells[1]?.innerText.trim() || '',
            cells[2]?.innerText.trim() || '',
            cells[3]?.innerText.trim() || '',
            cells[4]?.innerText.trim() || '',
            cells[5]?.innerText.trim() || '',
            cells[6]?.innerText.trim() || '',
            cells[7]?.innerText.replace(/₹|,/g,'').trim() || '',
            cells[8]?.innerText.replace(/₹|,/g,'').trim() || '',
            cells[9]?.innerText.replace(/₹|,/g,'').trim() || '',
            cells[10]?.innerText.trim() || ''
        ];

        csv += rowData.map(v => `"${v}"`).join(",") + "\n";
    });

    const blob = new Blob(["\ufeff" + csv], {
        type: 'text/csv;charset=utf-8;'
    });

    const url = URL.createObjectURL(blob);

    const a = document.createElement('a');
    a.href = url;
    a.download = 'unpaid_bills.csv';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);

    URL.revokeObjectURL(url);
}

document.getElementById('excelBtn')?.addEventListener('click', downloadExcelFromTable);</script>

</body>
</html>