<?php
session_start();
include('config.php');
$FileName = 'testimonials.php';
$stat = [];

// Alphanumeric CAPTCHA generation function
function generateCaptcha($length = 6) {
    $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
    $captcha = '';
    for ($i = 0; $i < $length; $i++) {
        $captcha .= $chars[random_int(0, strlen($chars) - 1)];
    }
    return $captcha;
}

// Only generate a new CAPTCHA if not POST (so it doesn't change before validation)
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['captcha'] = generateCaptcha(6);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['addnewrecord'])) {
    $errors = [];
    $requiredFields = ['name', 'emailid', 'message', 'captcha'];
    foreach ($requiredFields as $field) {
        if (empty($_POST[$field])) {
            $errors[] = ucfirst(str_replace('_', ' ', $field)) . " is required.";
        }
    }

    // CAPTCHA validation
    if (empty($_POST['captcha']) || $_POST['captcha'] != $_SESSION['captcha']) {
        $errors[] = "Invalid captcha. Please try again.";
        // Regenerate captcha on error
        $_SESSION['captcha'] = generateCaptcha(6);
    }

    if (empty($errors)) {
        $aryData = array(
            'token' => token('testimonials'),
            'name' => $_POST['name'],
            'emailid' => $_POST['emailid'],
            'message' => $_POST['message'],
        );
        $flgIn1 = $db->insertAry("testimonials", $aryData);
        $_SESSION['success'] = "Thank you for your feedback!";
        header("Location: $FileName");
        exit;
    } else {
        $stat['error'] = $errors;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Testimonials</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <?php include('inc_meta.php') ?>
    <style>
        .feedback-form {
            margin: 50px auto;
            max-width: 600px;
            padding: 20px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .captcha-box {
            font-size: 22px;
            font-weight: 700;
            letter-spacing: 4px;
            background: #ededed;
            padding: 8px 18px;
            border-radius: 4px;
            display: inline-block;
            user-select: none;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <!-- PAGE WRAP -->
    <div id="page-wrap">

        <!-- HEADER -->
        <?php include('inc_header.php') ?>
        <!-- END / HEADER -->

        <!-- SUB BANNER -->
        <section class="section-sub-banner bg-9">
            <div class="awe-overlay"></div>
            <div class="sub-banner">
                <div class="container">
                    <div class="text text-center">
                        <h2>Testimonials</h2>
                    </div>
                </div>
            </div>
        </section>
        <!-- END / SUB BANNER -->
        <div class="container-fluid">
            <h2 style="text-align: center;margin-top:20px">Provide your Feedback</h2>
            <div class="container">
                <?php
                if (!empty($_SESSION['success'])) {
                    echo '<div class="alert alert-success">'.$_SESSION['success'].'</div>';
                    unset($_SESSION['success']);
                }
                if (!empty($stat['error'])) {
                    foreach ($stat['error'] as $err) {
                        echo '<div class="alert alert-danger">'.$err.'</div>';
                    }
                }
                ?>
                <form class="feedback-form" id="feedbackForm" action="" method="post" enctype="multipart/form-data" autocomplete="off">
                    <input type="hidden" name="addnewrecord" value="1">
                    <div class="form-group">
                        <label for="name">Name:</label>
                        <input type="text" class="form-control" id="name" name="name" placeholder="Enter your name" required>
                    </div>
                    <div class="form-group">
                        <label for="email">Email:</label>
                        <input type="email" class="form-control" id="email" name="emailid" placeholder="Enter your email" required>
                    </div>
                    <div class="form-group">
                        <label for="feedback">Feedback:</label>
                        <textarea class="form-control" id="feedback" name="message" rows="4" placeholder="Your feedback" required></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-12 col-lg-12">
                            <span class="captcha-box form-control" style="text-align:center;"><?php echo $_SESSION['captcha']; ?></span><br>
                        </div>
                        <div class="col-md-12 col-lg-12">
                            <label for="captcha">Enter the captcha shown above:</label>
                            <input type="text" class="form-control" id="captcha" name="captcha" placeholder="Enter captcha" maxlength="6" required autocomplete="off">
                        </div>
                    </div>
                    <div style="display: flex; justify-content: center; margin-top: 20px;">
                        <button type="submit" class="btn btn-primary awe-btn awe-btn-default" style="margin-top:10px;">Submit</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- FOOTER -->
        <?php include('inc_footer.php') ?>
        <!-- END / FOOTER -->

    </div>
    <!-- END / PAGE WRAP -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.0.7/dist/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <!-- LOAD JQUERY -->
    <?php include('inc_js.php') ?>
</body>
</html>