<?php
require("header.php")
?>

<?php
// Cache Headers
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");



// Check if the form is submitted
if (isset($_POST['text1']) && isset($_POST['text2']) && isset($_POST['text3']) && isset($_POST['text4']) && isset($_POST['text5']) && isset($_POST['text6']) && isset($_POST['text8']) && isset($_POST['text9']) && isset($_POST['text10']) && isset($_POST['text11']) && isset($_POST['text12']) && isset($_POST['text13']) && isset($_POST['text14']) && isset($_POST['text15']) && isset($_POST['text16']) && isset($_POST['text17']) && isset($_POST['text18']) && isset($_POST['text19']) && isset($_POST['text20']) && isset($_POST['text21'])  && isset($_POST['text22'])) {
    $text1 = $_POST['text1'];
    $text2 = $_POST['text2'];
    $text3 = strtoupper($_POST['text3']);
    $text4 = strtoupper($_POST['text4']);
    $text5 = strtoupper($_POST['text5']);
    $text6 = $_POST['text6'];
    $text7 = $_POST['text7'];
    $text8 = strtoupper($_POST['text8']);
    $text9 = strtoupper($_POST['text9']);
    $text10 = strtoupper($_POST['text10']);
    $text11 = convertToFormattedNumber($_POST['text11']); // Convert text11 to formatted number
    $text12 = $_POST['text12'];
    $text13 = strtoupper($_POST['text13']);
    $text14 = strtoupper($_POST['text14']);
    $text15 = strtoupper($_POST['text15']);
    $text16 = $_POST['text16'];
    $text17 = $_POST['text17'];
    $text18 = $_POST['text18'];
    $text19 = strtoupper($_POST['text19']);
    $text20 = strtoupper($_POST['text20']);
    $text21 = strtoupper($_POST['text21']);
    $text22 = convertToFormattedNumber($_POST['text22']); // Convert text22 to formatted number

    // Image path
    $imagePath = 'img/gen/usps-label.jpeg';

    // Load the image
    $image = imagecreatefromjpeg($imagePath);

    // Define text color (black)
    $textColor = imagecolorallocate($image, 0, 0, 0);

    // Calculate the Y-coordinates for each text |||
    $y1 = 250;
    $y2 = 305;
    $y3 = 720;
    $y4 = 780;
    $y5 = 840;
    $y6 = 760;
    $y7 = 1020;
    $y8 = 1200;
    $y9 = 1270;
    $y10 = 1340;
    $y11 = 2125;
    $y12 = 250;
    $y13 = 305;
    $y14 = 720;
    $y15 = 780;
    $y16 = 840;
    $y17 = 760;
    $y18 = 1020;
    $y19 = 1200;
    $y20 = 1270;
    $y21 = 1340;
    $y22 = 2125;

    // Calculate the X-coordinates for each text ----
    $x1 = 640;
    $x2 = 640;
    $x3 = 280;
    $x4 = 280;
    $x5 = 280;
    $x6 = 1420;
    $x7 = 1370;
    $x8 = 380;
    $x9 = 380;
    $x10 = 380;
    $x11 = 480;
    $x12 = 2162;
    $x13 = 2162;
    $x14 = 1802;
    $x15 = 1802;
    $x16 = 1802;
    $x17 = 2950;
    $x18 = 2900;
    $x19 = 1950;
    $x20 = 1950;
    $x21 = 1950;
    $x22 = 2000;

    // Load font file
    $fontPath = 'img/gen/fonts/arial.ttf'; // Replace with the actual path to the font file
    $fontPath1 = 'img/gen/fonts/arialbd.ttf'; // Replace with the actual path to the font file

    // Define font size
    $fontSize = 55; // Font size for text8 to text14
    $fontSize1 = 31; // Font size for text1 to text7
    $fontSize2 = 80; // Font size for text1 to text7
    $fontSize3 = 47; // Font size for text1 to text7
    $fontSize4 = 4; // Font size for text1 to text7
    $fontSize5 = 38; // Font size for text1 to text7

    // // Define font color
    // $textColor1 = "#000"; 
    // $textColor = "#000"; 

    // Apply faux bold effect to text for each option
    applyFauxBoldText($image, $fontSize1, $x1, $y1, $textColor, $fontPath, $text1);
    applyFauxBoldText($image, $fontSize1, $x2, $y2, $textColor, $fontPath, $text2);
    applyFauxBoldText($image, $fontSize5, $x3, $y3, $textColor, $fontPath, $text3);
    applyFauxBoldText($image, $fontSize5, $x4, $y4, $textColor, $fontPath, $text4);
    applyFauxBoldText($image, $fontSize5, $x5, $y5, $textColor, $fontPath, $text5);
    applyFauxBoldText($image, $fontSize2, $x6, $y6, $textColor, $fontPath1, $text6);
    applyFauxBoldText($image, $fontSize3, $x7, $y7, $textColor, $fontPath, $text7);
    applyFauxBoldText($image, $fontSize3, $x8, $y8, $textColor, $fontPath, $text8);
    applyFauxBoldText($image, $fontSize3, $x9, $y9, $textColor, $fontPath, $text9);
    applyFauxBoldText($image, $fontSize3, $x10, $y10, $textColor, $fontPath, $text10);
    applyFauxBoldText($image, $fontSize, $x11, $y11, $textColor, $fontPath1, $text11);
    applyFauxBoldText($image, $fontSize1, $x12, $y12, $textColor, $fontPath, $text12);
    applyFauxBoldText($image, $fontSize1, $x13, $y13, $textColor, $fontPath, $text13);
    applyFauxBoldText($image, $fontSize5, $x14, $y14, $textColor, $fontPath, $text14);
    applyFauxBoldText($image, $fontSize5, $x15, $y15, $textColor, $fontPath, $text15);
    applyFauxBoldText($image, $fontSize5, $x16, $y16, $textColor, $fontPath, $text16);
    applyFauxBoldText($image, $fontSize2, $x17, $y17, $textColor, $fontPath1, $text17);
    applyFauxBoldText($image, $fontSize3, $x18, $y18, $textColor, $fontPath, $text18);
    applyFauxBoldText($image, $fontSize3, $x19, $y19, $textColor, $fontPath, $text19);
    applyFauxBoldText($image, $fontSize3, $x20, $y20, $textColor, $fontPath, $text20);
    applyFauxBoldText($image, $fontSize3, $x21, $y21, $textColor, $fontPath, $text21);
    applyFauxBoldText($image, $fontSize, $x22, $y22, $textColor, $fontPath1, $text22);

    // Set image quality
    $quality = 100;

    // Change the save path and filename as needed
    $timestamp = time();
    $savePath = "img/gen/usps/generated_image_$timestamp.jpg";
    imagejpeg($image, $savePath, $quality);

    // Free up memory
    imagedestroy($image);

    // Provide the URL of the saved image for preview and download
    $imageURL = $savePath;
} else {
    echo "Please enter all fourteen texts.";
}

function applyFauxBoldText($image, $fontSize, $x, $y, $color, $fontPath, $text)
{
    $offset = 1; // Adjust the offset to control the faux bold effect
    for ($i = 0; $i < $offset; $i++) {
        imagettftext($image, $fontSize, 0, $x + $i, $y, $color, $fontPath, $text);
    }
}

// Convert numeric number to formatted number
function convertToFormattedNumber($numericNumber)
{
    // Check if the numeric number is 20 characters long
    if (strlen($numericNumber) == 22) {
        // Split the numeric number into groups of 4 characters
        $formattedNumber = substr($numericNumber, 0, 4) . ' ' . substr($numericNumber, 4, 4) . ' ' . substr($numericNumber, 8, 4) . ' ' . substr($numericNumber, 12, 4) . ' ' . substr($numericNumber, 16, 4) . ' ' . substr($numericNumber, 20, 2);
        return $formattedNumber;
    } else {
        // If the numeric number doesn't have 20 characters, return it as is
        return $numericNumber;
    }
}

?>

<head>

    <style>
        table {
            border-collapse: collapse;
            width: 100%;
        }

        th,
        td {
            border: 1px solid black;
            padding: 8px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        @media (max-width: 576px) {
            .card-body .col-sm-1 .buttunMT {
                margin-top: 0% !important;
            }
        }
    </style>
</head>

<div class="content-wrapper">
    <!-- Content Header (Page header) -->


    <section class="content">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-12">
                    <!-- Form Column -->
                    <div class="card card-secondary">
                        <div class="card-header" style="background-color: black;">
                            <h3 class="card-title">Address Search</h3>

                            <!-- Your existing card header code here -->
                        </div>
                        <div class="card-body">

                            <div class="row">
                                <div class="col-12">
                                    <form method="post" action="">
                                        <div class="row">
                                            <div class="col-sm-11">
                                                <div class="form-group">
                                                    <label for="zip">Enter Zip Codes (separated by spaces or commas):</label>
                                                    <input type="text" class="form-control" id="zip" name="zip" required>
                                                </div>
                                            </div>
                                            <div class="col-sm-1">
                                                <button style="margin-top: 38%;width:95%; margin-left:5%; background:black;" type="submit" name="add" class="buttunMT btn btn-dark">Search</button>
                                            </div>
                                        </div>

                                    </form>
                                    <br>
                                    <?php
                                    include('connection.php');
                                    // User data array with zip codes
                                    $sql = "SELECT name, address FROM name_add";
                                    $result = mysqli_query($conn, $sql);

                                    // Initialize an empty array to store database results
                                    $userData = array();

                                    while ($row = mysqli_fetch_assoc($result)) {
                                        // Store the data in the format "name" => "address"
                                        $userData[$row['name']] = $row['address'];
                                    }

                                    // Initialize variables
                                    $searchZip = "";
                                    $searchResult = array();

                                    // Check if the form is submitted
                                    // Check if the form is submitted
                                    if ($_SERVER["REQUEST_METHOD"] == "POST") {
                                        $searchZip = $_POST["zip"]; // Ensure it matches the name attribute in the input field

                                        // Split the entered ZIP codes into an array
                                        $searchZipCodes = preg_split('/[\s,]+/', $searchZip);

                                        // Initialize an empty array to store search results
                                        $searchResults = [];

                                        // Loop through each entered ZIP code
                                        foreach ($searchZipCodes as $searchZip) {
                                            // Initialize variables for this ZIP code search
                                            $searchResult = [];

                                            // Loop through user data to find matching zip codes
                                            foreach ($userData as $name => $address) {
                                                $zipCode = substr($address, -5);

                                                if ($zipCode == $searchZip) {
                                                    $addressParts = explode(',', $address);
                                                    $firstPart = trim($addressParts[0]);
                                                    $secondPart = trim(end($addressParts));

                                                    $searchResult[$name] = [
                                                        'firstPart' => $firstPart,
                                                        'secondPart' => $secondPart
                                                    ];
                                                }
                                            }

                                            if (!empty($searchResult)) {
                                                $searchResults[$searchZip] = $searchResult;
                                            } else {
                                                $searchResults[$searchZip] = ["No results found"];
                                            }
                                        }

                                        if (empty($searchResults)) {
                                            $searchResults["No results found for any ZIP codes"] = [];
                                        }
                                    }

                                    ?>

                                    <?php
                                    // Display results in a Bootstrap table
                                    // Display results

                                    if (!empty($searchResults)) {
                                        echo '<section class="content">';
                                        echo '  <div class="container-fluid">';
                                        echo '    <div class="row">';
                                        echo '      <div class="col-12">';
                                        // echo '        <h3 class="mb-4">Search Results for ZIP Codes:</h3>';
                                        $tableCounter = 1; // Counter to distinguish tables

                                        foreach ($searchResults as $zip => $results) {
                                            if (count($results) > 0) {
                                                echo '<div class="card card-dark">';
                                                echo '  <div class="card-header">';
                                                echo '    <h5 class="card-title">Results for ZIP code ' . $zip . '</h5>';
                                                echo '  </div>';
                                                echo '  <div class="card-body">';
                                                echo '    <table class="table table-bordered">';
                                                echo '      <thead style="text-transform: uppercase;"><tr><th>Name</th><th>Address</th><th>City State Zip</th><th>Action</th></tr></thead>';
                                                echo '      <tbody>';
                                                foreach ($results as $name => $data) {
                                                    echo '        <tr>';
                                                    echo '          <td>' . $name . '</td>';
                                                    echo '          <td>' . $data['firstPart'] . '</td>';
                                                    echo '          <td>' . $data['secondPart'] . '</td>';
                                                    echo '          <td>';
                                                    echo '            <button class="btn btn-dark" onclick="fillForm(' . $tableCounter . ', \'' . $name . '\', \'' . $data['firstPart'] . '\', \'' . $data['secondPart'] . '\')">Fill Form</button>';
                                                    echo '          </td>';
                                                    echo '        </tr>';
                                                }
                                                echo '      </tbody>';
                                                echo '    </table>';
                                                echo '  </div>';
                                                echo '</div>';
                                                $tableCounter++; // Increment the table counter
                                            } else {
                                                echo '<p class="mt-4">No results found for ZIP code ' . $zip . '</p>';
                                            }
                                        }
                                        echo '      </div>';
                                        echo '    </div>';
                                        echo '  </div>';
                                        echo '</section>';
                                    } elseif ($_SERVER["REQUEST_METHOD"] == "POST") {
                                        echo '<p class="mt-4">No results found for any of the entered ZIP codes.</p>';
                                    }
                                    ?>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>


            </div>
        </div><!-- /.container-fluid -->
    </section>
    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-6">
                    <!-- Form Column -->
                    <div class="card card-secondary">
                        <div class="card-header" style="background-color: black;">
                            <h3 class="card-title">Create USPS Label</h3>
                            <ol class="breadcrumb float-right" style="background-color: black;">
                                <li class="breadcrumb-item">Tools</li>
                                <li class="breadcrumb-item active">USPS Label</li>
                            </ol>
                            <!-- Your existing card header code here -->
                        </div>
                        <div class="card-body">

                            <div class="row">

                                <div class="col-md-12">
                                    <form action="usps-address.php" method="post">

                                        <div class="row">
                                            <div class="col-lg-6">
                                                <label for="text1">Label 1</label>
                                                <div class="form-group">
                                                    <input type="text" class="form-control" id="text1" name="text1" placeholder="2023-06-12">
                                                </div>
                                                <div class="form-group">
                                                    <input type="text" class="form-control" id="text2" name="text2" placeholder="32658">
                                                </div>
                                                <div class="form-group">
                                                    <input type="text" class="form-control" id="text3" name="text3" placeholder="Paul Allen">
                                                </div>
                                                <div class="form-group">
                                                    <input type="text" class="form-control" id="text4" name="text4" placeholder="8 Leopolt St">
                                                </div>
                                                <div class="form-group">
                                                    <input type="text" class="form-control" id="text5" name="text5" placeholder="Burlington MA 36589">
                                                </div>
                                                <div class="form-group">
                                                    <input type="text" class="form-control" id="text6" name="text6" placeholder="0001">
                                                </div>
                                                <div class="form-group">
                                                    <input type="text" class="form-control" id="text7" name="text7" placeholder="C043">
                                                </div>
                                                <div class="form-group">
                                                    <input type="text" class="form-control" id="text8" name="text8" placeholder="Barbara Dembrowski">
                                                </div>
                                                <div class="form-group">
                                                    <input type="text" class="form-control" id="text9" name="text9" placeholder="2145 Pine Street">
                                                </div>
                                                <div class="form-group">
                                                    <input type="text" class="form-control" id="text10" name="text10" placeholder="Newhall CA 23658">
                                                </div>
                                                <div class="form-group">
                                                    <input type="text" class="form-control" id="text11" name="text11" placeholder="Newhall CA 23658">
                                                </div>
                                            </div>
                                            <div class="col-lg-6">
                                                <label for="text12">Label 1</label>
                                                <div class="form-group">
                                                    <input type="text" class="form-control" id="text12" name="text12" placeholder="2023-06-12">
                                                </div>
                                                <div class="form-group">
                                                    <input type="text" class="form-control" id="text13" name="text13" placeholder="32658">
                                                </div>
                                                <div class="form-group">
                                                    <input type="text" class="form-control" id="text14" name="text14" placeholder="Paul Allen">
                                                </div>
                                                <div class="form-group">
                                                    <input type="text" class="form-control" id="text15" name="text15" placeholder="8 Leopolt St">
                                                </div>
                                                <div class="form-group">
                                                    <input type="text" class="form-control" id="text16" name="text16" placeholder="Burlington MA 36589">
                                                </div>
                                                <div class="form-group">
                                                    <input type="text" class="form-control" id="text17" name="text17" placeholder="0001">
                                                </div>
                                                <div class="form-group">
                                                    <input type="text" class="form-control" id="text18" name="text18" placeholder="C043">
                                                </div>
                                                <div class="form-group">
                                                    <input type="text" class="form-control" id="text19" name="text19" placeholder="Barbara Dembrowski">
                                                </div>
                                                <div class="form-group">
                                                    <input type="text" class="form-control" id="text20" name="text20" placeholder="2145 Pine Street">
                                                </div>
                                                <div class="form-group">
                                                    <input type="text" class="form-control" id="text21" name="text21" placeholder="Newhall CA 23658">
                                                </div>
                                                <div class="form-group">
                                                    <input type="text" class="form-control" id="text22" name="text22" placeholder="3256 3656 2365 6545 6545 56">
                                                </div>
                                            </div>
                                        </div>
                                        <button type="submit" class="btn btn-primary mt-2" style="background:black;border:none">Generate Image</button>
                                    </form>
                                </div>
                                <div class="col-md-6">
                                    <!-- Placeholder for image previews or any other content -->
                                </div>
                            </div>

                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <!-- Image Preview Column -->
                    <div class="card card-secondary">
                        <div class="card-header" style="background-color: black;">
                            <h3 class="card-title">USPS Label Preview</h3>
                            <!-- Your existing card header code here -->
                        </div>
                        <div class="card-body">
                            <?php if (isset($imageURL)) : ?>
                                <img src="<?php echo $imageURL; ?>" alt="Generated Image" class="img-fluid">
                                <a href="<?php echo $imageURL; ?>" download class="btn btn-dark mt-2">Download Image</a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

            </div>
        </div><!-- /.container-fluid -->
    </section><!-- /.content -->
</div><!-- /.content-wrapper -->

<!-- Your existing scripts and footer here -->

<script>
    var loadFile = function(event) {
        var image = document.getElementById('output');
        image.src = URL.createObjectURL(event.target.files[0]);
    };
</script>
<script>
    function fillForm(tableNumber, text8, text9, text10) {
        // Populate the text fields with the provided data based on the table number
        switch (tableNumber) {
            case 1:
                document.getElementById('text3').value = text8;
                document.getElementById('text4').value = text9;
                document.getElementById('text5').value = text10;
                break;
            case 2:
                document.getElementById('text8').value = text8;
                document.getElementById('text9').value = text9;
                document.getElementById('text10').value = text10;
                break;
            case 3:
                document.getElementById('text14').value = text8;
                document.getElementById('text15').value = text9;
                document.getElementById('text16').value = text10;
                break;
            case 4:
                document.getElementById('text19').value = text8;
                document.getElementById('text20').value = text9;
                document.getElementById('text21').value = text10;
                break;
            default:
                break;
        }
    }
</script>
<!-- searching end -->

<!-- pagination -->

<?php
require("footer.php")
?>