<?php
require_once('tcpdf/tcpdf.php');

// echo $_FILES['csv_file']['error'];exit;

if ($_FILES['csv_file']['error'] === UPLOAD_ERR_OK) {
  // Step 1: Parse CSV File

  $data = [];
  if (($handle = fopen($_FILES['csv_file']['tmp_name'], 'r')) !== false) {
    while (($row = fgetcsv($handle, 1000, ',')) !== false) {
      $data[] = $row;
    }
    fclose($handle);
  } else {
    echo "Failed to open the file.";
  }

  // Step 2: Generate PDFs
  $tempDir = __DIR__ . '/temp_pdfs/';
  if (!is_dir($tempDir)) {
    mkdir($tempDir, 0777, true);
  }

  foreach ($data as $key => $row) {
    if ($key === 0) continue; // Skip header row

    $pdf = new TCPDF();
    $pdf->SetCreator(PDF_CREATOR);
    $pdf->SetAuthor('Your Company Name');
    $pdf->SetTitle('Invoice');

    // Add a page
    $pdf->AddPage();

    // Create PDF content
    if ($row[3] == 'NA') {
      $inv = str_replace(' ', '_', trim($row[2]));
    } else {
      $inv = $row[3];
    }

    $html = '
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invoice</title>
</head>
<body>
    <div class="invoice-box">
        <span style="text-align: center;"><h1>Invoice</h1></span>
        <br><br><br><br><br><br><br><br><br><br><br><br>
        <table>
            <tr class="top">
                <td>
                    <table>
                        <tr>
                            <td>MOBILE2WIN INDIA PRIVATE LIMITED<br>Abuzz, Solo India Building, Near Crescent Business<br>Square, Kherani Road, Opp Arma Hotel Gundecha<br>Onclave, Andheri East, Mumbai, Mumbai Suburban,<br>Maharashtra, 400072<br>
                            </td>
                            <td>
                                Invoice #: ' . $inv . '_' . str_pad($key, 5, '0', STR_PAD_LEFT) . '_' . date('Ymd', strtotime($row[1])).'<br>
                                Invoice Date: ' . date('d-m-Y', strtotime($row[1])) . '<br>
                                Biller Name: ' . $row[2] . '<br>
                                Account Holder Name: ' . $row[2] . '<br>
                                Account Number: ' . $row[7] . '<br>
                                Bank Name: <br>
                                PAN Number: ' . $row[3] . '<br>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
            <br><br><br><br>
            <tr>
                <table>
                    <tr>
                        <td style="border-bottom: 1px solid #000; border-left: none; border-right: none;">Station Code</td>
                        <td style="border-bottom: 1px solid #000; border-left: none; border-right: none;">Description</td>
                        <td style="border-bottom: 1px solid #000; border-left: none; border-right: none;">Gross Amount</td>
                        <td style="border-bottom: 1px solid #000; border-left: none; border-right: none;">Recovery</td>
                        <td style="border-bottom: 1px solid #000; border-left: none; border-right: none;">Net Amount</td>
                    </tr>
                    <tr>
                        <td>' . $row[8] . '</td>
                        <td>Delivery Charges</td>
                        <td>' . $row[4] . '</td>
                        <td>0.00</td>
                        <td>' . $row[4] . '</td>
                    </tr>
                    <tr class="total">
                        <td colspan="4" style="text-align: center; border-bottom: 1px solid #000; border-left: none; border-right: none;">SUB TOTAL:</td>
                        <td style="border-bottom: 1px solid #000; border-left: none; border-right: none;">' . $row[4] . '</td>
                    </tr>
                    <tr class="total">
                        <td colspan="4" style="text-align: center;">GRAND TOTAL:</td>
                        <td>' . $row[4] . '</td>
                    </tr>
                </table>
            </tr>
        </table>
        <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
        <div class="payment-instructions">
            <p>Invoice was created on a computer and is valid without the signature and seal.</p>
        </div>
    </div>
</body>
</html>
';


    // echo $html;exit;
    // Output content
    $pdf->writeHTML($html, true, false, true, false, '');
    $fileName = $tempDir . $inv . '_' . str_pad($key, 5, '0', STR_PAD_LEFT) . '_' . date('Ymd', strtotime($row[1])) . '.pdf';
    $pdf->Output($fileName, 'F');
  }

  // Step 3: Create ZIP File
  $zipFile = __DIR__ . '/invoices.zip';
  $zip = new ZipArchive();
  if ($zip->open($zipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
    $files = scandir($tempDir);
    foreach ($files as $file) {
      if ($file === '.' || $file === '..') continue;
      $zip->addFile($tempDir . $file, $file);
    }
    $zip->close();

    // Step 4: Serve ZIP File
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="invoices.zip"');
    header('Content-Length: ' . filesize($zipFile));
    readfile($zipFile);

    // Step 5: Clean up
    array_map('unlink', glob("$tempDir/*")); // Delete PDF files
    rmdir($tempDir); // Remove temporary directory
    unlink($zipFile); // Remove ZIP file after download
    exit;
  } else {
    echo 'Failed to create ZIP file.';
  }
} else {
  echo 'File upload error.';
}
