<?php
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'domain' => '',
    'secure' => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
    'httponly' => true,
    'samesite' => 'Lax'
]);
session_start();
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$errors = [];
$success = null;
$values = [
    'firstName' => '',
    'lastName' => '',
    'email' => '',
    'frequency' => 'biweekly'
];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $errors[] = 'Invalid submission token.';
    } else {
        $values['firstName'] = trim((string)($_POST['firstName'] ?? ''));
        $values['lastName'] = trim((string)($_POST['lastName'] ?? ''));
        $values['email'] = filter_var(trim((string)($_POST['email'] ?? '')), FILTER_SANITIZE_EMAIL);
        $values['frequency'] = trim((string)($_POST['frequency'] ?? 'biweekly'));
        $interests = isset($_POST['interests']) && is_array($_POST['interests']) ? $_POST['interests'] : [];
        $terms = isset($_POST['terms']);
        if ($values['firstName'] === '') $errors[] = 'First name is required.';
        if ($values['lastName'] === '') $errors[] = 'Last name is required.';
        if ($values['email'] === '' || !filter_var($values['email'], FILTER_VALIDATE_EMAIL)) $errors[] = 'Valid email is required.';
        if (!$terms) $errors[] = 'You must agree to Terms & Privacy Policy.';
        if (!$errors) {
            try {
                $dbDir = __DIR__ . '/../data';
                if (!is_dir($dbDir)) { @mkdir($dbDir, 0775, true); }
                $dbPath = $dbDir . '/site.db';
                $pdo = new PDO('sqlite:' . $dbPath);
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $pdo->exec('CREATE TABLE IF NOT EXISTS subscriptions (id INTEGER PRIMARY KEY AUTOINCREMENT, first_name TEXT, last_name TEXT, email TEXT UNIQUE, interests TEXT, frequency TEXT, ip TEXT, ua TEXT, created_at TEXT)');
                $stmt = $pdo->prepare('INSERT OR IGNORE INTO subscriptions (first_name,last_name,email,interests,frequency,ip,ua,created_at) VALUES (?,?,?,?,?,?,?,datetime("now"))');
                $stmt->execute([
                    $values['firstName'],
                    $values['lastName'],
                    $values['email'],
                    implode(', ', $interests),
                    $values['frequency'],
                    $_SERVER['REMOTE_ADDR'] ?? '',
                    $_SERVER['HTTP_USER_AGENT'] ?? ''
                ]);
            } catch (Throwable $t) {
                $logFile = ($dbDir ?? (__DIR__ . '/../data')) . '/errors.log';
                @file_put_contents($logFile, '[' . date('c') . '] DB error: ' . $t->getMessage() . "\n", FILE_APPEND);
            }
            $success = 'Thank you, ' . htmlspecialchars($values['firstName']) . '! You\'re subscribed.';
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
            $values = [
                'firstName' => '',
                'lastName' => '',
                'email' => '',
                'frequency' => 'biweekly'
            ];
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Subscribe to Newsletter - Home Enhancement</title>
    <meta name="description" content="Subscribe to Home Enhancement newsletter for exclusive design tips, project showcases, and special offers.">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;500;600;700&family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <header>
        <nav class="navbar navbar-expand-lg navbar-light fixed-top">
            <div class="container">
                <a class="navbar-brand" href="../index.html">
                    <span class="brand-text">HOME RENOVATE GUIDE</span>
                </a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNav">
                    <ul class="navbar-nav ms-auto">
                        <li class="nav-item">
                            <a class="nav-link" href="../index.html">Home</a>
                        </li>
                        <li class="nav-item dropdown">
                            <a class="nav-link dropdown-toggle" href="#" id="servicesDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">Services</a>
                            <ul class="dropdown-menu" aria-labelledby="servicesDropdown">
                                <li><a class="dropdown-item" href="services.html">All Services</a></li>
                                <li><hr class="dropdown-divider"></li>
                                <li><a class="dropdown-item" href="interior-design.html">Interior Design & Styling</a></li>
                                <li><a class="dropdown-item" href="furniture-selection.html">Furniture Selection & Placement</a></li>
                                <li><a class="dropdown-item" href="wall-art.html">Wall Art & Custom Decor</a></li>
                                <li><a class="dropdown-item" href="lighting-design.html">Lighting Design Solutions</a></li>
                                <li><a class="dropdown-item" href="flooring.html">Flooring & Carpeting Enhancements</a></li>
                                <li><a class="dropdown-item" href="outdoor-decor.html">Outdoor & Patio Decor</a></li>
                            </ul>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" aria-current="page" href="about.html">About Us</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="contact.php">Contact</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="subscribe.php">Subscribe</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
    </header>
    <section class="hero-section py-5" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
        <div class="container text-center text-white">
            <h1 class="display-4 fw-bold mb-4 text-white">Stay Updated with Home Enhancement</h1>
            <p class="lead mb-0">Get exclusive design tips, project showcases, and special offers delivered to your inbox</p>
        </div>
    </section>
    <section class="py-5">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-lg-8">
                    <?php if (!empty($errors)) { echo '<div class="alert alert-danger" role="alert"><ul class="mb-0">'; foreach ($errors as $e) { echo '<li>' . htmlspecialchars($e) . '</li>'; } echo '</ul></div>'; } ?>
                    <?php if ($success) { echo '<div class="alert alert-success" role="alert">' . $success . '</div>'; } ?>
                    <div class="card shadow-lg border-0">
                        <div class="card-body p-5">
                            <h2 class="text-center mb-4">Join Our Newsletter</h2>
                            <form id="subscribeForm" action="subscribe.php" method="POST" novalidate>
                                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="firstName" class="form-label">First Name *</label>
                                        <input type="text" class="form-control" id="firstName" name="firstName" value="<?php echo htmlspecialchars($values['firstName']); ?>" required>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="lastName" class="form-label">Last Name *</label>
                                        <input type="text" class="form-control" id="lastName" name="lastName" value="<?php echo htmlspecialchars($values['lastName']); ?>" required>
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <label for="email" class="form-label">Email Address *</label>
                                    <input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($values['email']); ?>" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Interests (Select all that apply)</label>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="interiorDesign" name="interests[]" value="Interior Design">
                                                <label class="form-check-label" for="interiorDesign">Interior Design</label>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="flooring" name="interests[]" value="Flooring Solutions">
                                                <label class="form-check-label" for="flooring">Flooring Solutions</label>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="lighting" name="interests[]" value="Lighting Design">
                                                <label class="form-check-label" for="lighting">Lighting Design</label>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="furniture" name="interests[]" value="Furniture Selection">
                                                <label class="form-check-label" for="furniture">Furniture Selection</label>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="wallArt" name="interests[]" value="Wall Art & Decor">
                                                <label class="form-check-label" for="wallArt">Wall Art & Decor</label>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="outdoor" name="interests[]" value="Outdoor Spaces">
                                                <label class="form-check-label" for="outdoor">Outdoor Spaces</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <label for="frequency" class="form-label">Email Frequency</label>
                                    <select class="form-select" id="frequency" name="frequency">
                                        <option value="weekly" <?php echo $values['frequency']==='weekly'?'selected':''; ?>>Weekly Updates</option>
                                        <option value="biweekly" <?php echo $values['frequency']==='biweekly'?'selected':''; ?>>Bi-weekly Updates</option>
                                        <option value="monthly" <?php echo $values['frequency']==='monthly'?'selected':''; ?>>Monthly Updates</option>
                                    </select>
                                </div>
                                <div class="form-check mb-4">
                                    <input class="form-check-input" type="checkbox" id="terms" name="terms" required>
                                    <label class="form-check-label" for="terms">I agree to the <a href="terms.html" target="_blank">Terms & Conditions</a> and <a href="privacy-policy.html" target="_blank">Privacy Policy</a></label>
                                </div>
                                <button type="submit" class="btn btn-primary btn-lg w-100">Subscribe Now</button>
                            </form>
                            <div class="text-center mt-4">
                                <img src="https://images.pexels.com/photos/6585744/pexels-photo-6585744.jpeg?auto=compress&cs=tinysrgb&w=1000&h=500" class="img-fluid rounded shadow" alt="Inspiration collage for home design newsletter" loading="lazy" width="1000" height="500">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <section class="py-5 bg-light">
        <div class="container">
            <h2 class="text-center mb-5">What You'll Get</h2>
            <div class="row">
                <div class="col-md-4 mb-4">
                    <div class="text-center">
                        <div class="bg-primary text-white rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width: 80px; height: 80px;">
                            <i class="fas fa-lightbulb fa-2x"></i>
                        </div>
                        <h4>Design Tips & Trends</h4>
                        <p>Stay ahead with the latest interior design trends and expert tips from our professional designers.</p>
                    </div>
                </div>
                <div class="col-md-4 mb-4">
                    <div class="text-center">
                        <div class="bg-primary text-white rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width: 80px; height: 80px;">
                            <i class="fas fa-images fa-2x"></i>
                        </div>
                        <h4>Project Showcases</h4>
                        <p>Get inspired by our latest home transformation projects and before-and-after galleries.</p>
                    </div>
                </div>
                <div class="col-md-4 mb-4">
                    <div class="text-center">
                        <div class="bg-primary text-white rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width: 80px; height: 80px;">
                            <i class="fas fa-tag fa-2x"></i>
                        </div>
                        <h4>Exclusive Offers</h4>
                        <p>Be the first to know about special discounts, seasonal promotions, and subscriber-only deals.</p>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <footer class="footer py-5">
        <div class="container">
            <div class="row">
                <div class="col-md-4 mb-4">
                    <h5>Home Renovate Guide</h5>
                    <p>Transforming spaces into beautiful, functional environments that reflect your unique style and personality.</p>
                </div>
                <div class="col-md-4 mb-4">
                    <h5>Quick Links</h5>
                    <ul class="footer-links">
                        <li><a href="../index.html">Home</a></li>
                        <li><a href="#">Services</a></li>
                        <li><a href="about.html">About Us</a></li>
                        <li><a href="contact.php">Contact</a></li>
                        <li><a href="subscribe.php">Subscribe</a></li>
                        <li><a href="privacy-policy.html">Privacy Policy</a></li>
                        <li><a href="terms.html">Terms & Conditions</a></li>
                    </ul>
                </div>
                <div class="col-md-4 mb-4">
                    <h5>Contact Us</h5>
                    <address>
                        <p><i class="fas fa-map-marker-alt me-2"></i> 81 Grapevine Rd <br> Oak View, California(CA), 93022</p>
                        <p><i class="fas fa-phone me-2"></i> (805) 649-4891</p>
                        <p><i class="fas fa-envelope me-2"></i> info@homerenovateguide.com</p>
                    </address>
                </div>
            </div>
            <hr>
            <div class="row">
                <div class="col-md-12 text-center">
                    <p class="copyright">© 2025 Home Renovate Guide. All Rights Reserved.</p>
                </div>
            </div>
        </div>
    </footer>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="../assets/js/main.js"></script>
</body>
</html>
