<!DOCTYPE html>
<html lang="ar">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>حسابات الدورة</title>
    <style>
      input::-webkit-outer-spin-button,
      input::-webkit-inner-spin-button {
      -webkit-appearance: none;
      margin: 0;
      }
      body {
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 100vh;
      font-family: Arial, sans-serif;
      direction: rtl;
      background-color: #ffffff;
      margin: 0;
      padding: 0;
      }
      .container {
      width: 100%;
      justify-content: center;
      /* Center horizontally */
      align-items: center;
      /* Center vertically */
      max-width: 650px;
      background-color: #DFE8F1;
      padding: 20px;
      border-radius: 8px;
      font-weight: bold;
      /* Make text bold 
      // box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      }
    </style>
    <style>
      .button {
      padding: 10px 20px;
      border: none;
      border-radius: 5px;
      color: white;
      cursor: pointer;
      font-size: 16px;
      margin: 5px;
      }
      .red {
      background-color: red;
      }
      .green {
      background-color: green;
      }
      .blue {
      background-color: blue;
      }
      .orange {
      background-color: orange;
      }
      .purple {
      background-color: purple;
      }
    </style>
    <style>
      table {
      width: 100%;
      background-color: #F0F8FF;
      border: 2px solid black;
      font-size: 18pt;
      border-collapse: collapse;
      margin: auto;
      }
      th,
      td {
      border: 1px solid black;
      padding: 5px;
      text-align: center;
      }
      th {
      color: blue;
      font-size: 25px;
      }
    </style>
    <style>
      input {
      font-weight: bold;
      /* Make text bold */
      width: 100%;
      padding: 0px;
      font-size: 20px;
      text-align: center;
      /* Center text horizontally */
      line-height: 1.0;
      /* Line height to center vertically */
      height: 30px;
      /* Set a fixed height if necessary */
      box-sizing: border-box;
      /* Ensures padding doesn't change the input height */
      }
      textarea {
      font-weight: bold;
      font-size: 22px;
      padding: 10px;
      width: 80%;
      height: 150px;
      box-sizing: border-box;
      /* Ensures padding doesn't affect the overall width */
      }
      .text-container {
      width: 80px;
      /* Adjust the width as needed */
      border: 1px solid #ccc;
      padding: 10px;
      word-wrap: break-word;
      /* Ensures long words wrap to the next line */
      overflow-wrap: break-word;
      /* Another way to achieve the same effect */
      word-break: break-word;
      /* Forces a break at the point of overflow */
      }
    </style>
    <style>
      /* Apply to table rows */
      tr {
      page-break-inside: avoid;
      }
    </style>
    <style>
      #capture {
      padding: 50px;
      /* Inner padding */
      border: 0px solid #ccc;
      background-color: #DFE8F1;
      display: inline-block;
      margin: 50px 0;
      /* Top and bottom margins */
      }
    </style>
    <style>
      @media print {
      .page-break {
      page-break-before: always;
      /* Forces a page break before this element */
      }
      /* To avoid breaks inside certain elements */
      .no-break {
      page-break-inside: avoid;
      /* Prevents breaking of this element */
      }
      }
    </style>
    <style>
      .negative {
      color: red;
      /* Change text color to red */
      font-weight: bold;
      /* Make the text bold */
      background-color: #ffe6e6;
      /* Light red background for emphasis */
      }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
  </head>
  <body>
    <div class="container" id="dataContainer">
      <table style="width: 650px; font-size:25px;">
        <tr>
          <td> حسابات بيع الدواجن </td>
          <td> عدد الفواتير: </td>
          <td><input type="number" id="cycle" step="0.01" style="font-size:22px; width: 50px; " /></td>
          <td><button class="button blue" onclick="calculate()">Save</button></td>
        </tr>
      </table>
      <table>
        <tr style="color: blue; font-size:25px;background-color: #a9cce3">
          <th> حسابات المسوقين</th>
        </tr>
      </table>
      <table id="myTable" style="font-size:26px;  width: 650px;">
        <thead>
          <tr>
            <th style="color: green; font-size:25px;">الاسم</th>
            <th style="color: green; font-size:25px;">الاقفاص</th>
            <th style="color: green; font-size:25px;">الوزن</th>
            <th style="color: green; font-size:25px;">التسعيرة</th>
            <th style="color: green; font-size:25px;">السعر</th>
            <th style="color: green; font-size:25px;">المدفوع</th>
          </tr>
        </thead>
        <tbody>
          <!-- Rows will be inserted here -->
        </tbody>
      </table>
	      <button class="button blue" onclick="deleteLastRow()">احذف اخر سطر</button>

	  
		           <script>
            // JavaScript to generate table rows
             const tableBody = document.querySelector("#myTable tbody");
			 // Define the number of rows you want
             const numberOfRows = 30;
; 
			 
            for (let i = 1; i <= numberOfRows; i++) {
                // Create a new row
                const row = document.createElement("tr");
            
                // Create cells for the row
                row.innerHTML = `
                    <td><input type="text" id="name${i}" name="name${i}"  minlength="4" maxlength="50" size="20" style="font-size:22px; width: 150px;" required /></td>
					<td><input type="number" id="box${i}" step="0.01" style="font-size:22px; width: 50px; background-color: #ebdef0;" /></td>
                    <td><input type="number" id="weight${i}" step="0.01" style="font-size:22px; width: 100px;" /></td>
                    <td><input type="number" id="price${i}" step="0.01" style="font-size:22px; width: 50px;" /></td>
                    <td id="load${i}" style=" background-color: #ebdef0; font-size:22px; width: 100px;">0</td>
                    <td><input type="number" id="payment${i}" step="0.01" style="font-size:22px; width: 100px;" /></td>
                `;
            
                // Append the row to the table body
                tableBody.appendChild(row);
            }
			
			        function deleteLastRow() {
            let table = document.getElementById('myTable');
            if (table.rows.length > 0) {
                table.deleteRow(table.rows.length - 1);
                saveData();
            }
        }
         </script>

      <table id="myTable2" style="font-size:26px;  width: 650px;">
        <tr>
          <th style="color: green; font-size:25px;">بيع اعلاف</th>
          <td><input type="number" id="extrafood" step="0.01" style="font-size:18px; width: 80px;"></td>
        </tr>
      </table>
	  
	  
	  
      <table>
        <tr style="color: blue; font-size:25px;;background-color: #a9cce3">
          <th>تفاصيل العدد</th>
        </tr>
      </table>
	  
	  
	  
      <table>
        <tr>
          <td style="color: green; font-size:18px;">عدد الصوص</td>
          <td style="color: green; font-size:18px;">الوفيات</td>
          <td style="color: green; font-size:18px;">الاقفاص</td>
          <td style="color: green; font-size:18px;">حمل القفص</td>
        </tr>
        <tr>
          <td><input type="number" id="thenumber" step="0.01" style="font-size:18px; width: 80px;"></td>
          <td><input type="number" id="dead" step="0.01" style="font-size:18px; width: 50px;"></td>
          <td><span id="boxes">0</span></td>
          <td><span id="Capacity">0</span></td>
        </tr>
      </table>
	  
	  
	  
      <table>
        <tr style="color: blue; font-size:25px;background-color: #a9cce3">
          <th> تفاصيل الوزن والتحويل</th>
        </tr>
      </table>
      <table style="width: 80%;   border: 2px solid black;  font-size: 18pt; width: 650px;">
        <tr>
          <td style="color: green; font-size:25px;">الاعلاف طن</td>
          <th style="color: green; font-size:25px;">الوزن الاجمالي</th>
          <th style="color: green; font-size:25px;"> التحويل </th>
          <th style="color: green; font-size:25px;"> التسعيرة الصفرية</th>
          <th style="color: green; font-size:25px;">البيع بدون خصم </th>
          <th style="color: green; font-size:25px;"> خصومات الفواتير </th>
        </tr>
        <tr>
          <td><input type="number" id="corn" step="0.01" style="font-size:22px; width: 100px;"></td>
          <td><span id="kgs">0</span></td>
          <td><span id="ratio">0</span></td>
          <td><span id="rate">0</span></td>
          <td> <span id="income">0</span></td>
          <td><span id="paycut">0</span></td>
        </tr>
      </table>
      <table>
        <tr style="background-color: #a9cce3; color: blue; font-size:25px;">
          <th>التكاليف بالدينار</th>
        </tr>
      </table>
      <table>
        <tr>
          <!--th style="color: green; font-size:18px;">العنصر</th-->
          <td>العلف</td>
          <td>دواء</td>
          <td>ماء</td>
          <td>كهرباء</td>
          <td>غاز</td>
        </tr>
        <tr>
          <!--th style="color: green; font-size:18px;">التكلفة</th-->
          <td><input type="number" id="feed" step="0.01"></td>
          <td><input type="number" id="medicine" step="0.01"></td>
          <td><input type="number" id="water" step="0.01"></td>
          <td><input type="number" id="electricity" step="0.01"></td>
          <td><input type="number" id="heating" step="0.01"></td>
        </tr>
      </table>
      <table>
        <tr>
          <!--th style="color: green; font-size:18px;">العنصر</th-->
          <td>كاش فواز</td>
          <td>كاش فائق</td>
          <td>ذمم</td>
          <td>دين كاش</td>
          <td>خصم وفيات</td>
        </tr>
        <tr>
          <!--th style="color: green; font-size:18px;">التكلفة</th-->
          <td><input type="number" id="cachfawaz" step="0.01"></td>
          <td><input type="number" id="cachfaeg" step="0.01"></td>
          <td><input type="number" id="else" step="0.01"></td>
          <td><input type="number" id="elsecash" step="0.01"></td>
          <td><input type="number" id="deathcut" step="0.01"></td>
        </tr>
      </table>
      <div class="page-break"></div>
      <table style="font-size:26px; width: 650px; " size="26">
        <tr>
          <th> تفاصيل</th>
        </tr>
        <tr>
          <td><textarea id="fawaz1" name="fawaz1" rows="6" cols="70" wrap="hard" style="font-size: 14pt; width: 630px;" placeholder=" تفاصيل الكاش"> </textarea></td>
        </tr>
      </table>
      <table>
        <tr style="color: blue; font-size:25px;background-color: #a9cce3">
          <th>الملخص للبيع</th>
        </tr>
      </table>
      <table style="width: 80%;  border: 2px solid black;  font-size: 18pt; width: 650px;">
        <tr>
          <th style="color: green; font-size:25px;">الايرادات</th>
          <th style="color: green; font-size:25px;"> التكلفة</th>
          <th style="color: green; font-size:25px;"> الربح</th>
        </tr>
        <tr>
          <td> <span id="incomeR">0</span></td>
          <td> <span id="cost">0</span></td>
          <td> <span id="profit">0</span></td>
        </tr>
      </table>
      <table>
        <th style="color: blue; font-size:25px;background-color: #a9cce3"> الحسابات النهائية بعد البيع</th>
      </table>
      <table>
        <!-- Titles Row -->
        <tr>
          <th colspan="2" class="title" style=" background-color: #fbeee6; border: 3px solid black;">توزيع الارباح</th>
          <th colspan="2" class="title" style=" background-color: #d1f2eb; border: 3px solid black;">صافي النقد</th>
        </tr>
        <!-- Column Headers Row -->
        <tr>
          <th style="color: green; font-size:25px; background-color: #fbeee6; border: 3px solid black;">فائق</th>
          <th style="color: green; font-size:25px; background-color: #fbeee6; border: 3px solid black;">فواز</th>
          <th style="color: green; font-size:25px; background-color: #d1f2eb; border: 3px solid black;">فائق</th>
          <th style="color: green; font-size:25px; background-color: #d1f2eb; border: 3px solid black;">فواز</th>
        </tr>
        <!-- Table Data Rows -->
        <tr>
          <td style="background-color: #fbeee6; border: 3px solid black;"><span id="faeg">0</span> </td>
          <td style="background-color: #fbeee6; border: 3px solid black;"><span id="fawaz">0</span> </td>
          <td style="background-color: #d1f2eb; border: 3px solid black;"><span id="faegnet">0</span> </td>
          <td style="background-color: #d1f2eb; border: 3px solid black;"><span id="fawaznet">0</span> </td>
        </tr>
      </table>
      <table>
        <tr>
          <td><button type="button" class="button red" onclick="clearData()">Clear Data</button></td>
          <td><button type="button" class="button green" onclick="printAsPDF()">Print as PDF</button></td>
          <td><input type="text" id="numericInput" placeholder="رقم الدورة" style="font-size:18px; width: 100px;" /></td>
          <!--td><button class="button green" onclick="saveAsPNG()">Generate PNG</button></td-->
          <td> <button id="saveButton" class="button green">Save as PNG</button></td>
          <td><button class="button blue" onclick="calculate()">Save</button></td>
        </tr>
      </table>
      <p class="date" id="currentDate"></p>
    </div>
    <!--div id="income"><span id="income">0</span></div-->
	
	
	<script>
			 
            function printAsPDF() {
                window.print();
            }
            function clearData() {
                // Select all input and textarea elements within the dataContainer div
                const inputs = document.querySelectorAll("#dataContainer input, #dataContainer textarea");
                
                // Clear the value of each input and textarea element
                inputs.forEach(input => input.value = "");
            }
       
            // Function to format the date to DD/MM/YYYY
            function formatDate(date) {
                const day = String(date.getDate()).padStart(2, '0');  // Get day and pad with zero if needed
                const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
                const year = date.getFullYear();
                return `${day}/${month}/${year}`;  // Return formatted date
            }
            
            // Get the current date
            const today = new Date();
            
            // Display the formatted date
            document.getElementById('currentDate').textContent = formatDate(today);
         </script>

 <script>
        function saveAsPNG() {
            const captureElement = document.getElementById('dataContainer');
            html2canvas(captureElement).then(canvas => {
                const imgData = canvas.toDataURL('image/png');

                // Get the numeric value from input
                const numericValue = document.getElementById('numericInput').value;

                // Define the file name with numeric value and text
                const fileName = `Report_${numericValue}.png`;
                console.log(fileName); // Output: Report_123.png

                // Create a link element to trigger the download
                const link = document.createElement('a');
                link.href = imgData;
                link.download = fileName; // Set the file name
                link.click(); // Trigger the download
            });
        }
    </script>
      
	  
	  
	  <script>
    // Load data from local storage into input fields
    function loadData() {
         for (let i = 1; i <= 30; i++) {
            document.getElementById('name' + i).value = localStorage.getItem('name' + i) || '';
			document.getElementById('box' + i).value = localStorage.getItem('box' + i) || '';
            document.getElementById('weight' + i).value = localStorage.getItem('weight' + i) || '';
            document.getElementById('price' + i).value = localStorage.getItem('price' + i) || '';
            document.getElementById('payment' + i).value = localStorage.getItem('payment' + i) || '';
        }

        const fields = ['feed', 'medicine', 'water', 'electricity', 'heating', 'cachfawaz', 'cachfaeg','deathcut','else','paycut','elsecash','extrafood', 'numericInput','cycle', 'corn','dead','thenumber'];
        fields.forEach(field => {
            document.getElementById(field).value = localStorage.getItem(field) || '';
        });

        document.getElementById('fawaz1').value = localStorage.getItem('fawaz1') || '';
         calculate();  // Call calculate after loading data
    }

    // Save input field data to local storage
    function saveData() {

        for (let i = 1; i <= 30; i++) {
            localStorage.setItem('name' + i, document.getElementById('name' + i).value);
			localStorage.setItem('box' + i, document.getElementById('box' + i).value);
            localStorage.setItem('weight' + i, document.getElementById('weight' + i).value);
            localStorage.setItem('price' + i, document.getElementById('price' + i).value);
            localStorage.setItem('payment' + i, document.getElementById('payment' + i).value);
        }

        const fields = ['feed', 'medicine', 'water', 'electricity', 'heating', 'cachfawaz', 'cachfaeg','deathcut','else','paycut','elsecash','extrafood', 'numericInput', 'cycle','corn','dead','thenumber'];
        fields.forEach(field => {
            localStorage.setItem(field, document.getElementById(field).value);
        });

        localStorage.setItem('fawaz1', document.getElementById('fawaz1').value);
     }

    // Perform calculations based on input values
    function calculate() {
        let totalIncome = 0;
        let totalPayment = 0;
        let totalWeight = 0;
		let totalBox = 0;
        for (let i = 1; i <= 30; i++) {
            const price = parseFloat(document.getElementById('price' + i).value) || 0;
            const box = parseFloat(document.getElementById('box' + i).value) || 0;
            const weight = parseFloat(document.getElementById('weight' + i).value) || 0;
            const payment = parseFloat(document.getElementById('payment' + i).value) || 0;

            const oneLoad = price * weight / 100;        
            document.getElementById('load' + i).innerText = oneLoad.toFixed(0);

            totalIncome += price * weight / 100; //parseFloat(document.getElementById('load' + i).value) || 0;
            totalPayment += payment;
            totalWeight += weight; 
			totalBox += box;
        }


       const extracorn=parseFloat(document.getElementById('extrafood').value) || 0;
	   const totalmoney=totalPayment+extracorn;


        const totalCost = calculateTotalCost();
        document.getElementById('cost').innerText = totalCost.toFixed(0);

        const totalRate = (totalWeight !== 0) ? (totalCost / totalWeight * 100) : 0;
        document.getElementById('rate').innerText = totalRate.toFixed(1);

        const totalRatio = totalWeight/(parseFloat(document.getElementById('corn').value || 0))/10 ;
        document.getElementById('ratio').innerText = totalRatio.toFixed(1);

       const AvgCapacity = ((parseFloat(document.getElementById('thenumber').value || 0))-(parseFloat(document.getElementById('dead').value || 0)))/totalBox
	   //(parseFloat(document.getElementById('thenumber').value || 0))-totalBox*11.35-(parseFloat(document.getElementById('dead').value || 0)) ;
       document.getElementById('Capacity').innerText = AvgCapacity.toFixed(1);


        document.getElementById('boxes').innerText = totalBox.toFixed(0);
        document.getElementById('kgs').innerText = totalWeight.toFixed(0);
        document.getElementById('income').innerText = totalIncome.toFixed(0);
        document.getElementById('incomeR').innerText = totalmoney.toFixed(0);

        const totalPayCut = totalIncome-totalPayment;
        document.getElementById('paycut').innerText = totalPayCut.toFixed(0);

        const totalProfit = totalmoney - totalCost;
        document.getElementById('profit').innerText = totalProfit.toFixed(0);

        const totalFaeg = 0.25 * totalProfit;
        document.getElementById('faeg').innerText = totalFaeg.toFixed(0);

        const totalFaegNet = totalFaeg + parseFloat(document.getElementById('cachfaeg').value || 0);
        document.getElementById('faegnet').innerText = totalFaegNet.toFixed(0);

        const totalFawaz = 0.75 * totalProfit;
        document.getElementById('fawaz').innerText = totalFawaz.toFixed(0);

        const totalFawazNet = totalFawaz + parseFloat(document.getElementById('cachfawaz').value || 0);
        document.getElementById('fawaznet').innerText = totalFawazNet.toFixed(0);

        // Highlight negative values
        highlightNegative('profit', totalProfit);
        highlightNegative('faeg', totalFaeg);
        highlightNegative('fawaz', totalFawaz);
        highlightNegative('faegnet', totalFaegNet);
        highlightNegative('fawaznet', totalFawazNet);

        saveData();  // Save data again after calculations
    }

    // Calculate total cost from various fields
    function calculateTotalCost() {
        const fields = ['feed', 'medicine', 'water', 'electricity', 'heating', 'cachfawaz', 'cachfaeg','else','deathcut','elsecash'];
        return fields.reduce((total, field) => {
            return total + (parseFloat(document.getElementById(field).value) || 0);
        }, 0);
    }

    // Highlight elements with negative values
    function highlightNegative(elementId, value) {
        const element = document.getElementById(elementId);
        if (value < 0) {
            element.classList.add('negative');
        } else {
            element.classList.remove('negative');
        }
    }

    // Load data when the window is loaded
    function addEventListeners() {

        for (let i = 1; i <= 30; i++) {
            document.getElementById('name' + i).addEventListener('input', saveData);
			document.getElementById('box' + i).addEventListener('input', saveData);
            document.getElementById('weight' + i).addEventListener('input', saveData);
            document.getElementById('price' + i).addEventListener('input', saveData);
            document.getElementById('payment' + i).addEventListener('input', saveData);
        }
        const fields = ['feed', 'medicine', 'water', 'electricity', 'heating', 'cachfawaz', 'cachfaeg','else','paycut','deathcut','elsecash','extrafood', 'numericInput', 'cycle','corn','dead','thenumber'];
        fields.forEach(field => {
            document.getElementById(field).addEventListener('input', saveData);
        });
        document.getElementById('fawaz1').addEventListener('input', saveData);
     }

    window.onload = function () {
	    addEventListeners();
        loadData();
    };
	</script>
	  
	  


<script>
    document.getElementById('saveButton').addEventListener('click', function() {
        var node = document.querySelector('.container');
        
        domtoimage.toPng(node)
            .then(function (dataUrl) {
                // Create a link element
                var link = document.createElement('a');
				
				// Get the numeric value from input
                const numericValue = document.getElementById('numericInput').value;

                // Define the file name with numeric value and text
                const fileName = `Report_${numericValue}.png`;
                console.log(fileName); // Output: Report_123.png

                // Set the download attribute with a filename
                link.download = fileName;
                // Set the href attribute to the data URL
                link.href = dataUrl;
                // Append the link to the body (required for some browsers)
                document.body.appendChild(link);
                // Trigger a click event on the link to download the image
                link.click();
                // Remove the link from the document
                document.body.removeChild(link);
            })
            .catch(function (error) {
                console.error('Oops, something went wrong!', error);
            });
    });
</script>
  </body>
</html>