<?php
// ==== File: /app/core/Database.php ====

class Database {
    private static $instance = null;
    private $conn;

    private $host = 'localhost';
    private $db = 'neradovi_survey';
    private $user = 'neradovi_surveyz';
    private $pass = 'c_p5H#eUd9.C';

    private function __construct() {
        try {
            $this->conn = new PDO("mysql:host={$this->host};dbname={$this->db};charset=utf8mb4", $this->user, $this->pass);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) {
            die("Connection failed: " . $e->getMessage());
        }
    }

    public static function getInstance() {
        if (!self::$instance) {
            self::$instance = new Database();
        }
        return self::$instance;
    }

    public function getConnection() {
        return $this->conn;
    }
}

// ==== File: /public/index.php ====

<?php include '../app/core/Database.php'; ?>
<!DOCTYPE html>
<html>
<head>
    <title>Start Survey</title>
</head>
<body>
    <form method="post" action="handle_start.php">
        <input type="text" name="name" placeholder="Name" required><br>
        <input type="email" name="email" placeholder="Email" required><br>
        <input type="text" name="company" placeholder="Company" required><br>
        <input type="text" name="region" placeholder="Region" required><br>
        <button type="submit">Continue</button>
    </form>
</body>
</html>

// ==== File: /public/handle_start.php ====

<?php
require_once '../app/core/Database.php';
$db = Database::getInstance()->getConnection();

$name = $_POST['name'];
$email = $_POST['email'];
$companyName = $_POST['company'];
$region = $_POST['region'];

$domain = explode('@', $email)[1];
$stmt = $db->prepare("SELECT * FROM companies WHERE domain = ? AND active_until >= CURDATE()");
$stmt->execute([$domain]);
$company = $stmt->fetch(PDO::FETCH_ASSOC);

$token = bin2hex(random_bytes(16));
$is_paid = $company ? 1 : 0;
$company_id = $company ? $company['id'] : null;

$stmt = $db->prepare("INSERT INTO users (name, email, company, region, survey_token, is_paid, company_id) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->execute([$name, $email, $companyName, $region, $token, $is_paid, $company_id]);

if ($company) {
    $db->prepare("UPDATE companies SET used_count = used_count + 1 WHERE id = ?")->execute([$company_id]);
    // Redirect to thank you page or email survey link
    header("Location: thank-you.php");
} else {
    // Redirect to Stripe Checkout (to be implemented)
    echo "Redirecting to Stripe...";
}

exit;

// ==== File: /public/survey.php ====

<?php
require_once '../app/core/Database.php';
$db = Database::getInstance()->getConnection();
$token = $_GET['token'] ?? '';

$stmt = $db->prepare("SELECT * FROM users WHERE survey_token = ?");
$stmt->execute([$token]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    die("Invalid survey token.");
}

// For demo: fetch all questions
$questions = $db->query("SELECT * FROM questions ORDER BY RAND()")->fetchAll(PDO::FETCH_ASSOC);
$current = $_GET['q'] ?? 0;
$question = $questions[$current] ?? null;

if (!$question) {
    header("Location: report.php?token=$token");
    exit;
}
?>
<!DOCTYPE html>
<html>
<head><title>Survey</title></head>
<body>
    <p>Question <?= $current + 1 ?> of <?= count($questions) ?>:</p>
    <form method="post" action="submit_answer.php">
        <p><?= htmlspecialchars($question['text']) ?></p>
        <?php for ($i = 1; $i <= 5; $i++): ?>
            <label><input type="radio" name="answer" value="<?= $i ?>" required> <?= $i ?></label><br>
        <?php endfor; ?>
        <input type="hidden" name="token" value="<?= $token ?>">
        <input type="hidden" name="question_id" value="<?= $question['id'] ?>">
        <input type="hidden" name="next_q" value="<?= $current + 1 ?>">
        <button type="submit">Next</button>
    </form>
</body>
</html>

// ==== File: /public/submit_answer.php ====

<?php
require_once '../app/core/Database.php';
$db = Database::getInstance()->getConnection();

$answer = $_POST['answer'];
$token = $_POST['token'];
$question_id = $_POST['question_id'];
$next_q = $_POST['next_q'];

$stmt = $db->prepare("SELECT id FROM users WHERE survey_token = ?");
$stmt->execute([$token]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$user) die("Invalid user.");

$stmt = $db->prepare("INSERT INTO answers (user_id, question_id, answer) VALUES (?, ?, ?)");
$stmt->execute([$user['id'], $question_id, $answer]);

header("Location: survey.php?token=$token&q=$next_q");
exit;

// ==== File: /public/report.php ====

<?php
require_once '../app/core/Database.php';
$db = Database::getInstance()->getConnection();

$token = $_GET['token'] ?? '';
$stmt = $db->prepare("SELECT id FROM users WHERE survey_token = ?");
$stmt->execute([$token]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$user) die("Invalid token.");

$stmt = $db->prepare("SELECT s.name AS segment, AVG(a.answer) AS avg_score
    FROM answers a
    JOIN questions q ON a.question_id = q.id
    JOIN segments s ON q.segment_id = s.id
    WHERE a.user_id = ?
    GROUP BY q.segment_id");
$stmt->execute([$user['id']]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head><title>Survey Report</title><script src="https://cdn.jsdelivr.net/npm/chart.js"></script></head>
<body>
<h2>Your Survey Report</h2>
<canvas id="chart" width="400" height="200"></canvas>
<script>
const ctx = document.getElementById('chart').getContext('2d');
new Chart(ctx, {
    type: 'bar',
    data: {
        labels: <?= json_encode(array_column($results, 'segment')) ?>,
        datasets: [{
            label: 'Average Score',
            data: <?= json_encode(array_map('floatval', array_column($results, 'avg_score'))) ?>,
            backgroundColor: 'rgba(54, 162, 235, 0.6)'
        }]
    },
    options: { scales: { y: { beginAtZero: true, max: 5 } } }
});
</script>
<a href="download.php?token=<?= $token ?>">Download PDF</a>
</body>
</html>