<!DOCTYPE html>
<html>
<head>
    <title>Daily Summaries</title>
    <style>
        /* CSS for the cards */
        #summaries-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
            grid-gap: 10px;
            padding: 20px; /* Add padding around the grid */
        }

        #summaries-container-totals {
            display: grid;
             grid-gap: 10px;
            padding: 20px; /* Add padding around the grid */
            justify-content: center;
        }


        .summary-card {
            font-size: 13px;
            border: 1px solid #ddd;
            padding: 15px;
            border-radius: 5px;
            box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
            transition: transform 0.2s;
            background-color: white;
            text-align: center;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            min-height: 150px; /* Ensure cards have a minimum height */
        }


        .totals-card{

            font-size: 16px;
            border: 1px solid #ddd;
            padding: 15px;
            border-radius: 5px;
            box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
            transition: transform 0.2s;
            background-color: white;
            text-align: center;
            display: flex;
           width: 400px;
            
            min-height: 150px; /* Ensure cards have a minimum height */

        }
        .summary-card:hover {
            transform: translateY(-5px);
            box-shadow: 4px 4px 8px rgba(0, 0, 0, 0.15);
        }

        .summary-card h3 {
            margin-top: 0;
            text-align: center;
            border-bottom: 1px solid #ddd;
            padding-bottom: 10px;
            margin-bottom: 10px;
        }

        .summary-card p {
            margin-bottom: 5px;
            text-align: left;
        }

        /* Styling for values (bold and different colors) */
        .summary-card .sales-value {
            font-weight: bold;
            color: #007bff; /* Blue */
        }

        .summary-card .withdrawals-value {
            font-weight: bold;
            color: #dc3545; /* Red */
        }

        .summary-card .expenses-value {
            font-weight: bold;
            color: #ffc107; /* Amber/Yellow */
        }

        .summary-card .profit-s-value {
            font-weight: bold;
            color: #28a745; /* Green */
        }
        #input-area{
            font-size: 10px;
            padding: 10px;
            display: flex;
            flex-direction: row;
            gap: 10px;

        }

        #input-area button{
           font-size: 10px;
          width: 40px;
          border-radius:15%;
          padding: 10px;
          justify-content: center;
        }
        .action-btns {
            width: 50%;
    display: flex; /* Arrange buttons horizontally */
    gap: 5px; /* Add some spacing between buttons */
    margin-bottom: 10px; /* Add margin below the buttons */
}

        #input-area button.active{
          
          border:1px #dc3545;
        }


        #error-message{
            color: red;
            padding: 20px;
        }
        #loading{
          display: none; /* Hide by default */
          text-align: center;
          font-size: 1.2em;
          margin-top: 20px;
        }
        .summary-card p {
    display: flex; /* Make the <p> a flex container */
    justify-content: space-between; /* Distribute space between label and value */
    align-items: center; /* Vertically align items */
    margin-bottom: 5px;
}

.summary-card p span {
    font-weight: bold;
   
    margin-left: auto; /* Push the span to the right */
}
      
    </style>
</head>
<body>

   

    <div id="input-area">
     <div class="action-btns">
<button id="today-btn">T</button>
<button id="yesterday-btn">Y</button>
<button id="week-btn">W</button>
<button id="month-btn">M</button>
</div>

<div style="display: none;">
        <label for="start-date">Start Date:</label>
        <input type="date" id="start-date"><br><br>

        <label for="end-date">End Date:</label>
        <input type="date" id="end-date"><br><br>

        <button id="fetch-summaries">Search</button>
    </div>
   </div>
    <div id="loading">Loading...</div>

   
    <div id="summaries-container"></div>
    <div id="summaries-container-totals"></div>
    <div id="error-message"></div>
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const companyId = sessionStorage.getItem("companyId");
            const startDateInput = document.getElementById("start-date");
            const endDateInput = document.getElementById("end-date");
            const fetchButton = document.getElementById("fetch-summaries");
            const summariesContainer = document.getElementById("summaries-container");
            const summariesContainerTotal = document.getElementById("summaries-container-totals");

            const loadingDiv = document.getElementById('loading');
            const errorDiv = document.getElementById("error-message");
            const todayBtn = document.getElementById('today-btn');
    const yesterdayBtn = document.getElementById('yesterday-btn');
    const weekBtn = document.getElementById('week-btn');
    const monthBtn = document.getElementById('month-btn');


   let defaultDate='';
   let startUpStockValue=0;
   let monthSelected=false;
            fetchButton.addEventListener("click", () => {
              
                const startDate = startDateInput.value;
                const endDate = endDateInput.value;
                errorDiv.textContent = "";

                if (!startDate || !endDate) {
                    errorDiv.textContent = "Please provide Company ID, Start Date, and End Date.";
                    return;
                }
               
                fetchAndDisplayDailySummaries(startDate, endDate);
            });


            async function fetchAndDisplayDailySummaries(startDate, endDate) {
                loadingDiv.style.display = 'block';
                summariesContainer.innerHTML = "";
                summariesContainerTotal .innerHTML="";
                try {
                    const url = `/api/all-total-summary/allBranch?companyId=${companyId}&startDate=${startDate}&endDate=${endDate}`;
                    const response = await fetch(url);

                    if (!response.ok) {
                        const errorData = await response.json();
                        throw new Error(errorData.message || "Failed to fetch daily summaries.");
                    }

                    const summaries = await response.json();
                    displaySummariesInCards(summaries);
                    loadingDiv.style.display = 'none';
                } catch (error) {
                    console.error("Error fetching or displaying summaries:", error);
                    errorDiv.textContent = error.message;
                    loadingDiv.style.display = 'none';
                }
            }
            // function displaySummariesInCards(summaries) {
            //     summariesContainer.innerHTML = "";

            //     if (!summaries || summaries.length === 0) {
            //         summariesContainer.innerHTML = "<p>No summaries found.</p>";
            //         return;
            //     }

            //     summaries.forEach(branchSummary => {
            //         const card = document.createElement("div");
            //         card.classList.add("summary-card");

            //         const data = branchSummary.data;
            //         const totalSales = Number(data?.totalSales) || 0;
            //         const totalStoreWithdrawal = Number(data?.totalStoreWithdrawal) || 0;
            //         const totalExpense = Number(data?.totalExpense) || 0;
            //         const ProfitS = Number(data?.dailyNetProfitUsingSystem) || 0;

            //         card.innerHTML = `
            //             <h3>${branchSummary.branchName}</h3>
            //             <p>Sales: <span class="sales-value">${totalSales.toFixed(2)}</span></p>
            //             <p>Withdrawals: <span class="withdrawals-value">${totalStoreWithdrawal.toFixed(2)}</span></p>
            //             <p>Expenses: <span class="expenses-value">${totalExpense.toFixed(2)}</span></p>
            //             <p>Profit-S: <span class="profit-s-value">${ProfitS.toFixed(2)}</span></p>
            //         `;

            //         summariesContainer.appendChild(card);
            //     });
            // }

          

//             function displaySummariesInCards(summaries) {
//      const summariesContainerTotal = document.getElementById("summaries-container-totals");
//     const summariesContainer = document.getElementById("summaries-container");
//     summariesContainer.innerHTML = "";
//     summariesContainerTotal .innerHTML="";
//     if (!summaries || summaries.length === 0) {
//         summariesContainer.innerHTML = "<p>No summaries found.</p>";
//         return;
//     }

//     // Initialize totals for each field
//     const totals = {
//         totalSales: 0,
//         toDaySale:0,
//         totalStoreWithdrawal: 0,
//         totalPurchases: 0,
//         totalExpense: 0,
//         bankDeposit: 0,
//         bankWithdraw: 0,
//         dailyNetProfitUsingSystem:0,
//         branchInventory:0
//     };

//     summaries.forEach(branchSummary => {
//         const data = branchSummary.data;

//         // Add to totals for each field
//         totals.branchInventory+= Number(branchSummary?.branchInventory) || 0;
//         totals.totalSales += Number(data?.totalSales) || 0;//system
//         totals.toDaySale += Number(data?.toDaySale) || 0;//cashier
//         totals.totalStoreWithdrawal += Number(data?.totalStoreWithdrawal) || 0;
//         totals.totalPurchases += Number(data?.totalPurchases) || 0;
//         totals.totalExpense += Number(data?.totalExpense) || 0;
//         totals.bankDeposit += Number(data?.bankDeposit) || 0;
//         totals.bankWithdraw += Number(data?.bankWithdraw) || 0;
//         totals.dailyNetProfitUsingSystem += Number(data?.dailyNetProfitUsingSystem) || 0;
   
//     });

//     const usedItems=startUpStockValue+totals.totalPurchases-totals.branchInventory;
//     const growthProfit=totals.toDaySale-usedItems-totals.totalExpense// befor rent and worker
//     // Create the totals card
//     const totalsCard = document.createElement("div");
//     totalsCard.classList.add("summary-card", "totals-card"); // Add totals-card class

//     totalsCard.innerHTML = `
//         <h3>Total Summaries</h3>
//         <p>System Sales: <span class="sales-value">${totals.totalSales.toFixed(2)}</span></p>
//         <p>Withdrawals: <span class="withdrawals-value">${totals.totalStoreWithdrawal.toFixed(2)}</span></p>
//          <p>Expenses: <span class="expenses-value">${totals.totalExpense.toFixed(2)}</span></p>
//            <p>Profit-S: <span class="profit-s-value">${totals.dailyNetProfitUsingSystem.toFixed(2)}</span></p>
//     `;
//     summariesContainerTotal.appendChild(totalsCard);
//     if(monthSelected){
//     const realGrowthProfit= document.createElement("div");
//     realGrowthProfit.classList.add("summary-card", "totals-card"); // Add totals-card class

//     realGrowthProfit.innerHTML = `
//         <h3>Real Growth Profit</h3>
//         <p>Cashier Sales: <span class="sales-value">${totals.toDaySale.toFixed(2)}</span></p>
//         <p>Withdrawals: <span class="withdrawals-value">${usedItems.toFixed(2)}</span></p>
//          <p>Expenses: <span class="expenses-value">${totals.totalExpense.toFixed(2)}</span></p>
//            <p> Growth Profit: <span class="profit-s-value">${growthProfit.toFixed(2)}</span></p>
//     `;

//     summariesContainerTotal.appendChild(realGrowthProfit);
//     }



//     // Create branch cards (same as before)
//     summaries.forEach(branchSummary => {
//         const card = document.createElement("div");
//         card.classList.add("summary-card");

//         const data = branchSummary.data;

//         card.innerHTML = `
//             <h3>${branchSummary.branchName}</h3>
//             <p>Sales: <span class="sales-value">${Number(data?.totalSales).toFixed(2) || 0}</span></p>
//             <p>Withdrawals: <span class="withdrawals-value">${Number(data?.totalStoreWithdrawal).toFixed(2) || 0}</span></p>
//             <p>Expenses: <span class="expenses-value">${Number(data?.totalExpense).toFixed(2) || 0}</span></p>
//             <p>Profit-S: <span class="profit-s-value">${Number(data?.dailyNetProfitUsingSystem).toFixed(2) || 0}</span></p>
//         `;

//         summariesContainer.appendChild(card);
//     });
// }



function displaySummariesInCards(summaries) {
    const summariesContainerTotal = document.getElementById("summaries-container-totals");
    const summariesContainer = document.getElementById("summaries-container");
    summariesContainer.innerHTML = "";
    summariesContainerTotal.innerHTML = "";

    if (!summaries || summaries.length === 0) {
        summariesContainer.innerHTML = "<p>No summaries found.</p>";
        return;
    }

    // Initialize totals for each field
    const totals = {
        totalSales: 0,
        toDaySale: 0,
        totalStoreWithdrawal: 0,
        totalStoreWithdrawalUsingSelling: 0,
        totalPurchases: 0,
        totalExpense: 0,
        bankDeposit: 0,
        bankWithdraw: 0,
        dailyNetProfitUsingSystem: 0,
        branchInventory: 0
    };

    summaries.forEach(branchSummary => {
        const data = branchSummary.data;

        // Add to totals for each field
        totals.branchInventory += Number(branchSummary?.branchInventory) || 0;
        totals.totalSales += Number(data?.totalSales) || 0; // system
        totals.toDaySale += Number(data?.toDaySale) || 0; // cashier
        totals.totalStoreWithdrawal += Number(data?.totalStoreWithdrawal) || 0;
        totals.totalPurchases += Number(data?.totalPurchases) || 0;
        totals.totalExpense += Number(data?.totalExpense) || 0;
        totals.bankDeposit += Number(data?.bankDeposit) || 0;
        totals.bankWithdraw += Number(data?.bankWithdraw) || 0;
        totals.dailyNetProfitUsingSystem += Number(data?.dailyNetProfitUsingSystem) || 0;
    });

    const usedItems = startUpStockValue + totals.totalPurchases - totals.branchInventory;
    const growthProfit = totals.toDaySale - usedItems - totals.totalExpense; // before rent and worker

    // Create the totals card
    const totalsCard = document.createElement("div");
    totalsCard.classList.add("summary-card", "totals-card"); // Add totals-card class

    totalsCard.innerHTML = `
        <h3>Total Summaries</h3>
        <p>System Sales: <span class="sales-value">${totals.totalSales.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span></p>
        <p>Withdrawals: <span class="withdrawals-value">${totals.totalStoreWithdrawal.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span></p>
        <p>Expenses: <span class="expenses-value">${totals.totalExpense.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span></p>
        <p>Profit-S: <span class="profit-s-value">${totals.dailyNetProfitUsingSystem.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span></p>
    `;
    summariesContainerTotal.appendChild(totalsCard);

    if (monthSelected) {
        const realGrowthProfit = document.createElement("div");
        realGrowthProfit.classList.add("summary-card", "totals-card"); // Add totals-card class

        realGrowthProfit.innerHTML = `
            <h3>Real Growth Profit</h3>
            <p>Cashier Sales: <span class="sales-value">${totals.toDaySale.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span></p>
            <p>Withdrawals: <span class="withdrawals-value">${usedItems.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span></p>
            <p>Expenses: <span class="expenses-value">${totals.totalExpense.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span></p>
            <p>Growth Profit: <span class="profit-s-value">${growthProfit.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span></p>
        `;
        summariesContainerTotal.appendChild(realGrowthProfit);
    }

    // Create branch cards (same as before)
    summaries.forEach(branchSummary => {
        const card = document.createElement("div");
        card.classList.add("summary-card");

        const data = branchSummary.data;

        card.innerHTML = `
            <h3>${branchSummary.branchName}</h3>
            <p>Sales: <span class="sales-value">${(Number(data?.totalSales) || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span></p>
            <p>Withdrawals: <span class="withdrawals-value">${(Number(data?.totalStoreWithdrawal) || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span></p>
            <p>Expenses: <span class="expenses-value">${(Number(data?.totalExpense) || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span></p>
            <p>Profit-S: <span class="profit-s-value">${(Number(data?.dailyNetProfitUsingSystem) || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span></p>
        `;
        summariesContainer.appendChild(card);
    });
}

    
    const getDates = (period) => {
        const today = new Date();
        let startDate, endDate;
        monthSelected=false;
        switch (period) {
            case 'today':
                startDate = today.toISOString().split('T')[0]; // YYYY-MM-DD
                endDate = today.toISOString().split('T')[0];
              
                break;
            case 'yesterday':
                const yesterday = new Date();
                yesterday.setDate(today.getDate() - 1);
                startDate = yesterday.toISOString().split('T')[0];
                endDate = yesterday.toISOString().split('T')[0];
             
                break;
            case 'week':
                const weekStart = new Date(today);
                weekStart.setDate(today.getDate() - today.getDay()); // Start of the week (Sunday)
                startDate = weekStart.toISOString().split('T')[0];
                endDate = today.toISOString().split('T')[0];

                break;
            case 'month':
                startDate = defaultDate;
                monthSelected=true;
                endDate = today.toISOString().split('T')[0];
                break;
            default:
                return null; // Or handle the error as you prefer
        }
        return { startDate, endDate };
    };



    async function getDefaultValues() {
        try {
          const response = await fetch(`/api/settings?companyId=${companyId}`);
          const data = await response.json();

          // Set default start date or fallback to today
          defaultDate = data.defaultStartDate ? data.defaultStartDate.split('T')[0] : getToday();
          startUpStockValue=data.startUpStockValue;
     
        } catch (error) {
          console.error('Error fetching default start date:', error);
        }
      }

      function getToday() {
        return new Date().toISOString().split('T')[0];
      }
    todayBtn.addEventListener('click', () => {
        const dates = getDates('today');
        if (dates) fetchAndDisplayDailySummaries(dates.startDate, dates.endDate);
    });

    yesterdayBtn.addEventListener('click', () => {
        const dates = getDates('yesterday');
        if (dates)  fetchAndDisplayDailySummaries(dates.startDate, dates.endDate);
    });

    weekBtn.addEventListener('click', () => {
        const dates = getDates('week');
        if (dates)  fetchAndDisplayDailySummaries(dates.startDate, dates.endDate);
    });

    monthBtn.addEventListener('click', () => {
        const dates = getDates('month');
        if (dates)  fetchAndDisplayDailySummaries(dates.startDate, dates.endDate);
    });

    getDefaultValues();

    // Initial fetch (optional - for today's data on page load):
    const initialDates = getDates('today');
   // if (initialDates) 
    // fetchAndDisplayDailySummaries(initialDates.startDate, initialDates.endDate);



        });
    </script>
