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

<?php
// Fetch settings
try {
    $stmt = $pdo->query("SELECT * FROM settings ORDER BY id DESC");
    $settings = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $numrows = count($settings);
} catch (PDOException $e) {
    echo "Error fetching settings: " . $e->getMessage();
}

// Handle form submission
if (isset($_POST['action'])) {
    // Sanitize inputs
    $cphone     = $_POST['cphone'];
    $cemail     = $_POST['cemail'];
    $cname      = $_POST['cname'];
    $id         = $_POST['id'];
    $app_id     = $_POST['app_id'];
    $ticket_id  = $_POST['ticket_id'];
    $email      = $_POST['email'];
    $name       = $_POST['name'];
    $phone      = $_POST['phone'];
    $re_msg     = $_POST['re_msg'];
    $title      = $_POST['title'];
    $date       = $_POST['date'];

    // Check if message already exists (optional)
    $checkStmt = $pdo->prepare("SELECT COUNT(*) FROM message WHERE ticket_id = ?");
    $checkStmt->execute([$ticket_id]);
    $enumrows = $checkStmt->fetchColumn();

    if ($enumrows < 1) {
        // Insert message
        try {
            $insertStmt = $pdo->prepare("INSERT INTO message (log_id, app_id, ticket_id, email, name, phone, note, title, status, date) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $insertStmt->execute([$id, $app_id, $ticket_id, $cemail, $cname, $cphone, $re_msg, $title, 2, $date]);

            $sucess = "<br><div class='alert alert-success'>
                <span class='closebtn'>&times;</span> 
                <center>
                    <div class='alert alert-success'>
                        <strong>Processing</strong><br>
                        <div class='loader'></div>
                    </div>
                </center>
                <meta http-equiv='refresh' content='8;url=' />
            </div>";

        } catch (PDOException $e) {
            echo "Error inserting message: " . $e->getMessage();
        }
    }

    // ======= To Admin =======
    if (isset($sucess)) {
        $to = $cemail;
        $subject = 'MESSAGE DELIVERED TO (' . htmlspecialchars($name) . ')';

        $body = "
        <p>Your message has been delivered to the contact details below:</p>
        NAME: " . htmlspecialchars($name) . "<br>
        PHONE: " . htmlspecialchars($phone) . "<br>
        EMAIL: " . htmlspecialchars($email) . "<br>
        MESSAGE: " . nl2br(htmlspecialchars($re_msg)) . "<br>";

        $header = "From: " . $email . "\r\n";
        $header .= "MIME-Version: 1.0\r\n";
        $header .= "Content-Type: text/html; charset=UTF-8\r\n";

        @mail($to, $subject, $body, $header);
    }

    // ======= To User =======
    if (isset($sucess)) {
        $to = $email;
        $subject = 'MESSAGE FROM ADMIN';

        $body = "
        <p>You have a new message from " . htmlspecialchars($cname) . ".</p>
        <center>
            <img id='logo' class='img-responsive' src='" . $url . "/img/LOGO.png' width='100%' height='100%' alt='logo'>
            " . nl2br(htmlspecialchars($re_msg)) . "
        </center>
        TITLE: " . htmlspecialchars($title) . "<br>
        PHONE: " . htmlspecialchars($cphone) . "<br>
        EMAIL: " . htmlspecialchars($cemail) . "<br>
        MESSAGE: " . nl2br(htmlspecialchars($re_msg)) . "<br>";

        $header = "From: " . $cemail . "\r\n";
        $header .= "MIME-Version: 1.0\r\n";
        $header .= "Content-Type: text/html; charset=UTF-8\r\n";

        @mail($to, $subject, $body, $header);
    }
}
?>

<div class="main-panel">
    <div class="content bg-light">
        <div class="page-inner">
            <div class="mt-2 mb-4">
                <h1 class="title1 text-dark">REPLY INBOX</h1>
            </div>

            <div class="mb-5 row">
                <div class="col-md-12 ">

                    <div class="page-breadcrumb">
                        <div class="row">
                            <div class="col-12 d-flex no-block align-items-center">
                                <h4 class="page-title">Reply Message</h4>
                                <div class="ml-auto text-right">
                                    <nav aria-label="breadcrumb">
                                        <ol class="breadcrumb">
                                            <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                                            <li class="breadcrumb-item active" aria-current="page">Message Details</li>
                                        </ol>
                                    </nav>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="container-fluid">

                        <?php if (isset($sucess)) { echo $sucess; } ?>

                        <?php
                        // Validate and sanitize $id from GET
                        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;

                        try {
                            $stmt = $pdo->prepare("SELECT * FROM message WHERE id = ?");
                            $stmt->execute([$id]);
                            $ordrow = $stmt->fetch(PDO::FETCH_ASSOC);

                            if ($ordrow):
                        ?>

                        <div class='card'>
                            <div class='card-body wizard-content'>
                                <h4 class='card-title'>Reply messages</h4>

                                <form class='form-horizontal' action='' method='post'>
                                    <div class='card-body'>

                                        <input type='hidden' class='form-control' name='id' value='<?= htmlspecialchars($ordrow['log_id']) ?>' readonly>

                                        <div class='form-group row'>
                                            <label for='name' class='col-sm-3 text-right control-label col-form-label'>Name</label>
                                            <div class='col-sm-9'>
                                                <input type='text' class='form-control' name='name' value='<?= htmlspecialchars($ordrow['name']) ?>' readonly>
                                            </div>
                                        </div>

                                        <div class='form-group row'>
                                            <label for='email' class='col-sm-3 text-right control-label col-form-label'>Email</label>
                                            <div class='col-sm-9'>
                                                <input type='email' class='form-control' name='email' value='<?= htmlspecialchars($ordrow['email']) ?>' readonly>
                                            </div>
                                        </div>

                                        <div class='form-group row'>
                                            <label for='app_id' class='col-sm-3 text-right control-label col-form-label'>APP - ID</label>
                                            <div class='col-sm-9'>
                                                <input type='text' class='form-control' name='app_id' value='<?= htmlspecialchars($ordrow['app_id']) ?>' readonly>
                                            </div>
                                        </div>

                                        <div class='form-group row'>
                                            <label for='phone' class='col-sm-3 text-right control-label col-form-label'>Mobile Number</label>
                                            <div class='col-sm-9'>
                                                <input type='text' class='form-control' name='phone' value='<?= htmlspecialchars($ordrow['phone']) ?>'>
                                            </div>
                                        </div>

                                        <div class='form-group row'>
                                            <label for='title' class='col-sm-3 text-right control-label col-form-label'>Title</label>
                                            <div class='col-sm-9'>
                                                <input type='text' class='form-control' name='title' value='RE:<?= htmlspecialchars($ordrow['title']) ?>'>
                                            </div>
                                        </div>

                                        <div class='form-group row'>
                                            <label for='re_msg' class='col-sm-3 text-right control-label col-form-label'>Message</label>
                                            <div class='col-sm-9'>
                                                <textarea name='re_msg' id='editor1' class='form-control'><?= htmlspecialchars($ordrow['note']) ?></textarea>
                                                <script>CKEDITOR.replace('editor1');</script>
                                            </div>
                                        </div>

                                        <input type="hidden" class="form-control" name="date" id="details"  value="<?php echo(date("jS F Y g.iA")); ?>"  readonly/><br>

                                        <?php
                                        try {
                                            $stmt = $pdo->query("SELECT * FROM settings ORDER BY id DESC");
                                            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
                                            foreach ($rows as $row) {
                                                echo "
                                                <input type='hidden' class='form-control' name='cname' id='details' value='" . htmlspecialchars($row['domain_name']) . "'>
                                                <input type='hidden' class='form-control' name='cemail' id='details' value='" . htmlspecialchars($row['email2']) . "'>
                                                <input type='hidden' class='form-control' name='cphone' id='details' value='" . htmlspecialchars($row['phone']) . "'>
                                                ";
                                            }
                                        } catch (PDOException $e) {
                                            echo "<div class='alert alert-danger'>Error fetching settings: " . $e->getMessage() . "</div>";
                                        }
                                        ?>

                                        <div class="col-md-12">
                                            <div class="form-group app-label">
                                                <label for="edit_personal_email" class="control-label">Ticket ID</label>
                                                <?php $ticket_id = rand(10000000000000,100000000000000); ?>
                                                <input name="ticket_id" type="number" class="form-control"  value="<?php echo $ticket_id; ?>" readonly>  
                                            </div>
                                        </div>

                                    </div>

                                    <div class='border-top'>
                                        <div class='card-body'>
                                            <button type='submit' name='action' class='btn btn-primary'>Submit</button>
                                        </div>
                                    </div>
                                </form>

                            </div>
                        </div>

                        <?php
                            else:
                                echo "<div class='alert alert-danger'>Message not found.</div>";
                            endif;

                        } catch (PDOException $e) {
                            echo "<div class='alert alert-danger'>Error: " . $e->getMessage() . "</div>";
                        }
                        ?>

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

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