<?php
// phpcs:disable WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.InputNotValidated
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber
// phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
if (!defined('ABSPATH')) { exit; }

/**
 * YATOON_Reviews
 *
 * Handles:
 *  1. Creating a review record (with unique token) when a booking is confirmed
 *  2. Sending the star-rating email X hours after appointment ends
 *  3. Public shortcode [yatoon_reviews] to display approved reviews (Pro)
 *  4. Admin management page
 *  5. AJAX: submit rating + text, approve/reject, feature
 */
class YATOON_Reviews {

    public function __construct() {
        // Hook into booking created to schedule review request
        add_action('yatoon_booking_created', array($this, 'schedule_rating_request'), 30, 1);

        // Cron action
        add_action('yatoon_send_rating_request', array($this, 'send_rating_email'), 10, 1);

        // Public: handle rating submission (tokenised URL)
        add_action('init', array($this, 'handle_rating_submission'));

        // Public shortcode (Pro only for display)
        add_shortcode('yatoon_reviews', array($this, 'reviews_shortcode'));

        // AJAX: admin actions
        add_action('wp_ajax_yatoon_review_action', array($this, 'ajax_review_action'));
    }

    // -------------------------------------------------------------------------
    // Schedule rating request after booking created
    // -------------------------------------------------------------------------

    public function schedule_rating_request($booking) {
        if (get_option('yatoon_rating_enabled', '1') !== '1') return;
        if (empty($booking['customer_email']) || empty($booking['end_time'])) return;

        $booking_id = $booking['booking_id'] ?? '';
        if (empty($booking_id)) return;

        // Create review record with unique token
        $this->create_review_record($booking);

        $hours_after = max(1, intval(get_option('yatoon_rating_hours_after', 3)));
        $send_ts     = strtotime($booking['end_time']) + ($hours_after * HOUR_IN_SECONDS);

        if ($send_ts > time() && !wp_next_scheduled('yatoon_send_rating_request', array($booking_id))) {
            wp_schedule_single_event($send_ts, 'yatoon_send_rating_request', array($booking_id));
        }
    }

    private function create_review_record($booking) {
        global $wpdb;
        $table = $wpdb->prefix . 'yatoon_reviews';

        $booking_id = absint($booking['booking_id'] ?? 0);
        if (!$booking_id) return;

        // Don't duplicate
        $exists = $wpdb->get_var($wpdb->prepare("SELECT id FROM $table WHERE booking_id = %d LIMIT 1", $booking_id));
        if ($exists) return;

        $token = wp_generate_password(32, false);

        $wpdb->insert($table, array(
            'booking_id'    => $booking_id,
            'customer_name' => sanitize_text_field($booking['customer_name'] ?? ''),
            'customer_email'=> sanitize_email($booking['customer_email'] ?? ''),
            'service_name'  => sanitize_text_field($booking['service_name'] ?? ''),
            'staff_name'    => sanitize_text_field($booking['staff_name'] ?? ''),
            'token'         => $token,
            'status'        => 'pending',
        ));
    }

    // -------------------------------------------------------------------------
    // Send rating request email
    // -------------------------------------------------------------------------

    public function send_rating_email($booking_id) {
        if (get_option('yatoon_rating_enabled', '1') !== '1') return;

        global $wpdb;
        $bookings_table = $wpdb->prefix . 'yatoon_bookings';
        $reviews_table  = $wpdb->prefix . 'yatoon_reviews';

        $booking = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $bookings_table WHERE id = %d LIMIT 1", absint($booking_id)
        ));
        if (!$booking || empty($booking->customer_email)) return;

        // Skip cancelled bookings
        if (in_array($booking->status, array('CANCELLED_BY_CUSTOMER','CANCELLED_BY_SELLER','DECLINED','cancelled'), true)) return;

        $review = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $reviews_table WHERE booking_id = %d LIMIT 1", absint($booking_id)
        ));
        if (!$review) return;

        $business_name  = get_option('yatoon_business_name', get_bloginfo('name'));
        $primary_color  = get_option('yatoon_primary_color', '#C2185B');
        $submit_base    = home_url('/');
        $rating_subject = get_option('yatoon_rating_subject', 'How was your visit to {business_name}?');
        $rating_subject = str_replace('{business_name}', $business_name, $rating_subject);

        $first_name = explode(' ', $booking->customer_name, 2)[0] ?: 'there';

        // Build 5-star row
        $stars_html = '';
        $star_labels = array(1=>'Poor', 2=>'Fair', 3=>'Good', 4=>'Great', 5=>'Amazing!');
        for ($i = 1; $i <= 5; $i++) {
            $url = add_query_arg(array(
                'yatoon_rate' => '1',
                'token'       => $review->token,
                'rating'      => $i,
            ), $submit_base);
            $stars_html .= '<a href="' . esc_url($url) . '" style="text-decoration:none;margin:0 4px;display:inline-block;">'
                . '<div style="width:52px;height:52px;border-radius:50%;background:' . ($i >= 4 ? $primary_color : '#f3f4f6') . ';display:flex;align-items:center;justify-content:center;font-size:22px;line-height:52px;text-align:center;">'
                . '*'
                . '</div>'
                . '<div style="font-size:10px;text-align:center;color:#6b7280;margin-top:4px;">' . $star_labels[$i] . '</div>'
                . '</a>';
        }

        $service_line = $booking->service_name ? '<p style="color:#6b7280;font-size:14px;margin:4px 0 0;">' . esc_html($booking->service_name) . ' · ' . gmdate('M j', strtotime($booking->start_time)) . '</p>' : '';

        $html = '
<div style="font-family:-apple-system,BlinkMacSystemFont,\'Segoe UI\',sans-serif;max-width:520px;margin:0 auto;padding:32px 24px;color:#111827;background:#fff;">
    <h2 style="font-size:22px;font-weight:700;margin:0 0 6px;">How was your visit? *</h2>
    <p style="font-size:15px;color:#374151;margin:0 0 24px;">Hi ' . esc_html($first_name) . ', thank you for visiting <strong>' . esc_html($business_name) . '</strong>!</p>
    ' . $service_line . '
    <p style="font-size:14px;color:#6b7280;margin:20px 0 16px;">Tap a star to rate your experience:</p>
    <div style="display:flex;justify-content:center;gap:8px;margin:0 0 28px;text-align:center;">' . $stars_html . '</div>
    <p style="font-size:12px;color:#9ca3af;border-top:1px solid #f3f4f6;padding-top:16px;margin:0;">
        This rating request was sent by ' . esc_html($business_name) . '. Reply to this email if you have questions.
    </p>
</div>';

        wp_mail(
            $booking->customer_email,
            $rating_subject,
            $html,
            array('Content-Type: text/html; charset=UTF-8')
        );
    }

    // -------------------------------------------------------------------------
    // Handle public submission (tokenised URL click)
    // -------------------------------------------------------------------------

    public function handle_rating_submission() {
        if (empty($_GET['yatoon_rate']) || empty($_GET['token'])) return;

        $token  = sanitize_text_field(wp_unslash($_GET['token']));
        $rating = isset($_GET['rating']) ? min(5, max(1, intval($_GET['rating']))) : 0;

        global $wpdb;
        $table  = $wpdb->prefix . 'yatoon_reviews';
        $review = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table WHERE token = %s LIMIT 1", $token));

        if (!$review) {
            wp_die(esc_html__('This rating link is invalid or has expired.', 'yatoon-booking-system'));
        }

        // If already submitted with text, just show thank-you
        if ($review->status === 'approved' || $review->status === 'submitted') {
            $this->render_thankyou_page($review);
            exit;
        }

        // If rating clicked from email (GET), store it and show text form
        if ($rating && $review->status === 'pending') {
            $wpdb->update($table,
                array('rating' => $rating, 'status' => 'submitted', 'submitted_at' => current_time('mysql')),
                array('token' => $token),
                array('%d', '%s', '%s'), array('%s')
            );
            $review->rating = $rating;
            $review->status = 'submitted';
        }

        // POST: additional text submitted
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['yatoon_review_nonce'])) {
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['yatoon_review_nonce'])), 'yatoon_submit_review_' . $token)) {
                wp_die(esc_html__('Security check failed.', 'yatoon-booking-system'));
            }
            $text = sanitize_textarea_field(wp_unslash($_POST['review_text'] ?? ''));
            $new_rating = isset($_POST['rating']) ? min(5, max(1, intval($_POST['rating']))) : $review->rating;
            $auto_approve = get_option('yatoon_rating_auto_approve', '1') === '1';
            $wpdb->update($table,
                array(
                    'rating'       => $new_rating,
                    'review_text'  => $text,
                    'status'       => $auto_approve ? 'approved' : 'submitted',
                    'submitted_at' => current_time('mysql'),
                ),
                array('token' => $token),
                array('%d', '%s', '%s', '%s'), array('%s')
            );
            $review->rating      = $new_rating;
            $review->review_text = $text;
            $review->status      = $auto_approve ? 'approved' : 'submitted';
            $this->render_thankyou_page($review);
            exit;
        }

        $this->render_rating_form($review, $token);
        exit;
    }

    private function render_rating_form($review, $token) {
        $business_name = get_option('yatoon_business_name', get_bloginfo('name'));
        $primary_color = get_option('yatoon_primary_color', '#C2185B');
        $stars = array(1=>'😞 Poor', 2=>'😐 Fair', 3=>'🙂 Good', 4=>'😊 Great', 5=>'🤩 Amazing!');
        $current = intval($review->rating ?? 5);
        ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Rate your visit - <?php echo esc_html($business_name); ?></title>
<style>
*{box-sizing:border-box;margin:0;padding:0;}
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:#f9fafb;display:flex;align-items:center;justify-content:center;min-height:100vh;padding:24px;}
.card{background:#fff;border-radius:16px;padding:36px 32px;max-width:460px;width:100%;box-shadow:0 4px 24px rgba(0,0,0,.08);}
h2{font-size:22px;font-weight:700;color:#111827;margin-bottom:6px;}
.sub{color:#6b7280;font-size:14px;margin-bottom:28px;}
.stars{display:flex;gap:10px;justify-content:center;margin-bottom:24px;}
.star-btn{background:none;border:2px solid #e5e7eb;border-radius:50%;width:52px;height:52px;font-size:22px;cursor:pointer;transition:all .15s;}
.star-btn.active,.star-btn:hover{border-color:<?php echo esc_attr($primary_color); ?>;background:<?php echo esc_attr($primary_color); ?>;color:#fff;}
textarea{width:100%;border:1px solid #e5e7eb;border-radius:8px;padding:12px;font-size:14px;font-family:inherit;min-height:100px;resize:vertical;margin-bottom:16px;color:#111827;}
textarea:focus{outline:none;border-color:<?php echo esc_attr($primary_color); ?>;}
.submit-btn{width:100%;background:<?php echo esc_attr($primary_color); ?>;color:#fff;border:none;border-radius:8px;padding:14px;font-size:16px;font-weight:600;cursor:pointer;}
.submit-btn:hover{opacity:.9;}
.star-label{text-align:center;font-size:13px;color:#6b7280;height:20px;margin-bottom:16px;}
</style>
</head>
<body>
<div class="card">
    <h2>How was your visit? *</h2>
    <p class="sub">Hi <?php echo esc_html(explode(' ', $review->customer_name, 2)[0] ?: 'there'); ?>, thanks for visiting <?php echo esc_html($business_name); ?>!</p>
    <form method="POST">
        <?php wp_nonce_field('yatoon_submit_review_' . $token, 'yatoon_review_nonce'); ?>
        <input type="hidden" name="yatoon_rate" value="1">
        <input type="hidden" name="token" value="<?php echo esc_attr($token); ?>">
        <input type="hidden" name="rating" id="rating-input" value="<?php echo esc_attr($current); ?>">
        <div class="stars">
            <?php for ($i = 1; $i <= 5; $i++): ?>
            <button type="button" class="star-btn<?php echo esc_attr( $i <= $current ? ' active' : '' ); ?>" data-val="<?php echo esc_attr( $i ); ?>">�?/button>
            <?php endfor; ?>
        </div>
        <div class="star-label" id="star-label"><?php echo esc_html($stars[$current] ?? ''); ?></div>
        <textarea name="review_text" placeholder="Tell us more about your experience (optional)..."><?php echo esc_textarea($review->review_text ?? ''); ?></textarea>
        <button type="submit" class="submit-btn">Submit Review</button>
    </form>
</div>
<script>
const labels = {1:'😞 Poor',2:'😐 Fair',3:'🙂 Good',4:'😊 Great',5:'🤩 Amazing!'};
document.querySelectorAll('.star-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        const val = parseInt(btn.dataset.val);
        document.getElementById('rating-input').value = val;
        document.getElementById('star-label').textContent = labels[val] || '';
        document.querySelectorAll('.star-btn').forEach((b,i) => {
            b.classList.toggle('active', i < val);
        });
    });
});
</script>
</body>
</html>
        <?php
    }

    private function render_thankyou_page($review) {
        $business_name  = get_option('yatoon_business_name', get_bloginfo('name'));
        $google_link    = get_option('yatoon_review_google_link', '');
        $primary_color  = get_option('yatoon_primary_color', '#C2185B');
        $rating         = intval($review->rating ?? 5);
        ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Thank you - <?php echo esc_html($business_name); ?></title>
<style>
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:#f9fafb;display:flex;align-items:center;justify-content:center;min-height:100vh;padding:24px;}
.card{background:#fff;border-radius:16px;padding:48px 32px;max-width:420px;width:100%;box-shadow:0 4px 24px rgba(0,0,0,.08);text-align:center;}
.icon{font-size:48px;margin-bottom:16px;}
h2{font-size:24px;font-weight:700;color:#111827;margin-bottom:8px;}
p{color:#6b7280;font-size:15px;line-height:1.6;margin-bottom:24px;}
.google-btn{display:inline-block;background:<?php echo esc_attr($primary_color); ?>;color:#fff;padding:12px 28px;border-radius:8px;text-decoration:none;font-weight:600;font-size:15px;}
</style>
</head>
<body>
<div class="card">
    <div class="icon"><?php echo esc_html( $rating >= 4 ? '🎉' : '🙏' ); ?></div>
    <h2>Thank you<?php echo esc_html( $rating >= 4 ? '!' : ' for your feedback' ); ?></h2>
    <p>Your <?php echo esc_html( $rating ); ?>-star rating has been received. We appreciate you taking the time - it helps us improve and helps others find us.</p>
    <?php if ($google_link && $rating >= 4): ?>
    <p style="font-size:14px;color:#374151;">Love us? A quick Google review would mean the world to us! 🙏</p>
    <a href="<?php echo esc_url($google_link); ?>" target="_blank" class="google-btn">Leave a Google Review *</a>
    <?php endif; ?>
</div>
</body>
</html>
        <?php
    }

    // -------------------------------------------------------------------------
    // Shortcode [yatoon_reviews] - Pro only for public display
    // -------------------------------------------------------------------------

    public function reviews_shortcode($atts) {
        $is_pro = class_exists('YATOON_License') && YATOON_License::is_pro();
        if (!$is_pro) {
            return '<p style="color:#9ca3af;font-size:13px;border:1px dashed #e5e7eb;padding:12px;border-radius:8px;">
                <strong>Yatoon Reviews</strong> - upgrade to Pro to display customer reviews on your website.
            </p>';
        }

        $atts = shortcode_atts(array('limit' => 10, 'min_rating' => 4), $atts);
        global $wpdb;
        $table   = $wpdb->prefix . 'yatoon_reviews';
        $reviews = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM $table WHERE status = 'approved' AND rating >= %d ORDER BY submitted_at DESC LIMIT %d",
            intval($atts['min_rating']), intval($atts['limit'])
        ));

        if (empty($reviews)) return '';

        $primary = get_option('yatoon_primary_color', '#C2185B');
        $out  = '<div class="yatoon-reviews-grid" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:16px;margin:24px 0;">';
        foreach ($reviews as $r) {
            $rating = max(0, min(5, intval($r->rating)));
            $stars = str_repeat('*', $rating) . str_repeat('-', 5 - $rating);
            $initials = strtoupper(substr($r->customer_name, 0, 1) ?: 'G');
            $out .= '<div style="background:#fff;border:1px solid #e5e7eb;border-radius:12px;padding:20px;">';
            $out .= '<div style="display:flex;align-items:center;gap:12px;margin-bottom:12px;">';
            $out .= '<div style="width:40px;height:40px;border-radius:50%;background:' . esc_attr($primary) . ';color:#fff;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:16px;">' . esc_html($initials) . '</div>';
            $out .= '<div><strong style="font-size:14px;">' . esc_html($r->customer_name ?: 'Guest') . '</strong>';
            if ($r->service_name) $out .= '<div style="font-size:12px;color:#9ca3af;">' . esc_html($r->service_name) . '</div>';
            $out .= '</div></div>';
            $out .= '<div style="color:#f59e0b;font-size:18px;margin-bottom:8px;">' . esc_html($stars) . '</div>';
            if ($r->review_text) $out .= '<p style="font-size:14px;color:#374151;line-height:1.6;margin:0;">' . esc_html($r->review_text) . '</p>';
            $out .= '</div>';
        }
        $out .= '</div>';
        return $out;
    }

    // -------------------------------------------------------------------------
    // AJAX: admin review actions (approve / reject / feature / delete)
    // -------------------------------------------------------------------------

    public function ajax_review_action() {
        check_ajax_referer('yatoon_admin_nonce', 'nonce');
        if (!current_user_can('manage_options')) wp_send_json_error();

        global $wpdb;
        $table  = $wpdb->prefix . 'yatoon_reviews';
        $id     = absint($_POST['id'] ?? 0);
        $action = sanitize_key($_POST['review_action'] ?? '');

        if (!$id) wp_send_json_error(array('message' => 'Missing ID'));

        switch ($action) {
            case 'approve':
                $wpdb->update($table, array('status' => 'approved'), array('id' => $id));
                break;
            case 'reject':
                $wpdb->update($table, array('status' => 'rejected'), array('id' => $id));
                break;
            case 'feature':
                $current = $wpdb->get_var($wpdb->prepare("SELECT is_featured FROM $table WHERE id = %d", $id));
                $wpdb->update($table, array('is_featured' => $current ? 0 : 1), array('id' => $id));
                break;
            case 'delete':
                $wpdb->delete($table, array('id' => $id));
                break;
            default:
                wp_send_json_error(array('message' => 'Unknown action'));
        }

        wp_send_json_success();
    }
}
