<?php
// CRITICAL: Ensure config.php is required first.
require_once 'config.php';

// --- Data Fetching Setup ---
$slug = $_GET['slug'] ?? '';
$profile = null;
$page_title = 'Profile Not Found | ' . APP_NAME;
$meta_description = 'The requested profile was not found or is currently under review.';

// Initialize variables for the template
$profile_found = false;
$testimonials = [];
$avg_rating_formatted = 'N/A';
$total_ratings = 0;

// Load any flash messages that might have been set during POST redirect
$errors = $_SESSION['errors'] ?? [];
$success_message = $_SESSION['success_message'] ?? null;
unset($_SESSION['errors'], $_SESSION['success_message']);


// --- TESTIMONIAL SUBMISSION POST HANDLER ---
if (!empty($slug) && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'submit_review') {
    
    // 1. Validate CSRF
    if (!validate_csrf_token($_POST['csrf_token'] ?? '')) {
        $_SESSION['errors']['csrf'] = 'Invalid request token. Please refresh and try again.';
        redirect('/u/' . $slug);
    }

    $name = trim($_POST['reviewer_name'] ?? '');
    $email = filter_var(trim($_POST['reviewer_email'] ?? ''), FILTER_SANITIZE_EMAIL);
    $rating = max(1, min(5, (int)($_POST['rating'] ?? 5))); // Clamp rating between 1 and 5
    $comment = trim($_POST['comment'] ?? '');

    if (empty($name) || empty($comment) || empty($email)) {
        $_SESSION['errors']['review'] = 'Name, email, and comment are required.';
        redirect('/u/' . $slug);
    }

    $user_id = is_logged_in() ? $_SESSION['user_id'] : null;

    try {
        // Find the profile ID to attach the review
        $stmt_profile_id = $pdo->prepare("SELECT id FROM profiles WHERE slug = ? AND status = 'approved'");
        $stmt_profile_id->execute([$slug]);
        $profile_id_review = $stmt_profile_id->fetchColumn();

        if ($profile_id_review) {
            $stmt = $pdo->prepare("INSERT INTO testimonials 
                (profile_id, reviewer_user_id, reviewer_name, reviewer_email, rating, comment, created_at, status)
                VALUES (?, ?, ?, ?, ?, ?, NOW(), 'pending')");
            
            $stmt->execute([$profile_id_review, $user_id, $name, $email, $rating, $comment]);
            $_SESSION['success_message'] = 'Thank you! Your review has been submitted and is pending admin approval.';
        } else {
            $_SESSION['errors']['db'] = 'Cannot submit review; profile not found or not approved.';
        }
        
        // Redirect to clear POST data and show message
        redirect('/u/' . $slug);

    } catch (PDOException $e) {
        error_log("Review Submission Error: " . $e->getMessage());
        $_SESSION['errors']['db'] = 'A database error occurred. Could not submit review.';
        redirect('/u/' . $slug);
    }
}
// --- END POST HANDLER ---


// --- GET CONTENT FETCH ---
if (!empty($slug)) {
    try {
        // 5.3 Query: SELECT * FROM profiles WHERE slug=? AND status='approved'.
        $stmt = $pdo->prepare("SELECT * FROM profiles WHERE slug = ? AND status = 'approved'");
        $stmt->execute([$slug]);
        $profile = $stmt->fetch();

        if ($profile) {
            $profile_found = true;
            
            // NEW: Fetch Gallery Photos (Feature 1)
$stmt_photos = $pdo->prepare("SELECT photo_url, description FROM profile_photos WHERE profile_id = ? ORDER BY sort_order ASC");
$stmt_photos->execute([$profile['id']]);
$gallery_photos = $stmt_photos->fetchAll();

// NEW: Fetch Working Hours (Feature 2)
$stmt_hours = $pdo->prepare("SELECT day_of_week, open_time, close_time, is_closed FROM working_hours WHERE profile_id = ? ORDER BY FIELD(day_of_week, 'Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday')");
$stmt_hours->execute([$profile['id']]);
$working_hours = $stmt_hours->fetchAll();
            
            // 5.3 SEO: Set page title and meta description
            $name_display = htmlspecialchars($profile['business_name'] ?: $profile['full_name']);
            $page_title = $name_display . ' – ' . htmlspecialchars($profile['category']) . ' in Chikhali | ' . APP_NAME;
            $meta_description = htmlspecialchars(substr($profile['headline'] . ' ' . $profile['about'], 0, 150));
            
            // Fetch Approved Testimonials
            $stmt_reviews = $pdo->prepare("SELECT reviewer_name, rating, comment, created_at 
                                           FROM testimonials 
                                           WHERE profile_id = ? AND status = 'approved'
                                           ORDER BY created_at DESC");
            $stmt_reviews->execute([$profile['id']]);
            $testimonials = $stmt_reviews->fetchAll();

            // Calculate average rating
            $total_ratings = count($testimonials);
            if ($total_ratings > 0) {
                $avg_rating = array_sum(array_column($testimonials, 'rating')) / $total_ratings;
                $avg_rating_formatted = number_format($avg_rating, 1);
            }
        }

    } catch (PDOException $e) {
        error_log("Profile Page DB Error: " . $e->getMessage());
        // If DB fails, let the final render handle the 404
    }
} 
// --- END GET CONTENT FETCH ---


// --- Final Render ---
if (!$profile_found) {
    http_response_code(404);
}

include 'templates/main_template.php';
?>