<?php
if (!defined('ABSPATH')) exit;

function bestserve_crm_lead_detail($atts = []) {
    $atts = shortcode_atts(['lead_id' => 0], $atts);
    $lead_id = intval($atts['lead_id']) ?: (isset($_GET['lead_id']) ? intval($_GET['lead_id']) : 0);
    if (!$lead_id) return "<p>Lead not found.</p>";

    // Fetch meta
    $first_name = get_post_meta($lead_id,'first_name',true);
    $last_name  = get_post_meta($lead_id,'last_name',true);
    $email      = get_post_meta($lead_id,'email',true);
    $phone      = get_post_meta($lead_id,'phone',true);
    $address    = get_post_meta($lead_id,'address',true);
    $city       = get_post_meta($lead_id,'city',true);
    $zipcode    = get_post_meta($lead_id,'zipcode',true);
    $req_date   = get_post_meta($lead_id,'requested_date',true);
    $req_time   = get_post_meta($lead_id,'requested_time',true);
    $status     = get_post_meta($lead_id,'status',true) ?: 'Lead';
    $next_followup = get_post_meta($lead_id,'next_followup_date',true);
    $lost_reason = get_post_meta($lead_id,'lost_reason',true);

    // Status update
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
        $new_status = sanitize_text_field($_POST['lead_status']);
        update_post_meta($lead_id,'status',$new_status);

        if ($new_status === 'Lost Sale' && ! empty($_POST['lost_reason'])) {
            update_post_meta($lead_id,'lost_reason', sanitize_text_field($_POST['lost_reason']));
        } else {
            delete_post_meta($lead_id,'lost_reason');
        }

        $status = $new_status;
        echo '<p class="crm-success">✅ Status updated!</p>';
    }

    // Communication log
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_log'])) {
        $log_entry = sanitize_textarea_field($_POST['comm_log']);
        $followup_date = sanitize_text_field($_POST['followup_date']);

        $logs = get_post_meta($lead_id,'communication_log',true) ?: [];
        $logs[] = [
            'log' => $log_entry,
            'date' => current_time('Y-m-d H:i:s'),
            'followup' => $followup_date,
            'by' => wp_get_current_user()->display_name ?: 'Unknown'
        ];
        update_post_meta($lead_id,'communication_log',$logs);

        if (! empty($followup_date)) {
            update_post_meta($lead_id,'next_followup_date',$followup_date);
            $next_followup = $followup_date;
        }

        echo '<p class="crm-success">✅ Communication added!</p>';
    }

    ob_start(); ?>
    
    <div class="crm-lead-detail">
        <h2 class="crm-title"><?php echo esc_html($first_name . ' ' . $last_name); ?> <span class="crm-sub">Lead Detail</span></h2>

        <!-- Lead Info -->
        <div class="crm-card">
            <h3>📌 Lead Information</h3>
            <p><strong>Email:</strong> <?php echo esc_html($email); ?></p>
            <p><strong>Phone:</strong> <?php echo esc_html($phone); ?></p>
            <p><strong>Address:</strong> <?php echo esc_html($address); ?></p>
            <p><strong>City:</strong> <?php echo esc_html($city); ?></p>
            <p><strong>Zipcode:</strong> <?php echo esc_html($zipcode); ?></p>
            <p><strong>Requested Date:</strong> <?php echo esc_html($req_date); ?></p>
            <p><strong>Requested Time:</strong> <?php echo esc_html($req_time); ?></p>
            <p><strong>Status:</strong> <span class="status-badge"><?php echo esc_html($status); ?></span></p>
            <p><strong>Next Follow-up:</strong> <?php echo esc_html($next_followup ?: 'Not set'); ?></p>
        </div>

        <!-- Status Update -->
        <div class="crm-card">
            <h3>🔄 Update Status</h3>
            <form method="post">
                <select name="lead_status" class="crm-input">
                    <option value="Lead" <?php selected($status,'Lead'); ?>>Lead</option>
                    <option value="Follow Up" <?php selected($status,'Follow Up'); ?>>Follow Up</option>
                    <option value="Closed" <?php selected($status,'Closed'); ?>>Closed</option>
                    <option value="Lost Sale" <?php selected($status,'Lost Sale'); ?>>Lost Sale</option>
                </select>

                <div id="lost-reason-wrapper" style="<?php echo ($status==='Lost Sale') ? '' : 'display:none;'; ?>">
                    <label>Reason for Lost Sale</label>
                    <select name="lost_reason" class="crm-input">
                        <option value="">Select reason</option>
                        <option value="Expensive" <?php selected($lost_reason,'Expensive'); ?>>Expensive</option>
                        <option value="Done elsewhere" <?php selected($lost_reason,'Done elsewhere'); ?>>Done elsewhere</option>
                        <option value="No response" <?php selected($lost_reason,'No response'); ?>>No response</option>
                        <option value="Service not provided" <?php selected($lost_reason,'Service not provided'); ?>>Service not provided</option>
                        <option value="Installer/Technician unavailable" <?php selected($lost_reason,'Installer/Technician unavailable'); ?>>Installer/Technician unavailable</option>
                        <option value="Duplicate lead" <?php selected($lost_reason,'Duplicate lead'); ?>>Duplicate lead</option>
                    </select>
                </div>

                <button type="submit" name="update_status" class="crm-button">💾 Save Status</button>
            </form>
        </div>

        <!-- Communication Log -->
        <div class="crm-card">
            <h3>✉️ Communication Log</h3>
            <form method="post">
                <textarea name="comm_log" class="crm-input" rows="3" required placeholder="Add notes..."></textarea>
                <label>Next follow-up date (optional)</label>
                <input type="date" name="followup_date" value="<?php echo esc_attr($next_followup); ?>" class="crm-input">
                <button type="submit" name="add_log" class="crm-button">➕ Add Log</button>
            </form>

            <h4 style="margin-top:15px;">Previous Logs</h4>
            <?php
            $logs = get_post_meta($lead_id,'communication_log',true) ?: [];
            if ($logs) {
                echo '<ul class="crm-logs">';
                foreach ($logs as $l) {
                    echo '<li><strong>' . esc_html($l['date']) . ' (' . esc_html($l['by']) . '):</strong> ' . esc_html($l['log']);
                    if (!empty($l['followup'])) echo ' <span class="followup-badge">Next follow-up: ' . esc_html($l['followup']) . '</span>';
                    echo '</li>';
                }
                echo '</ul>';
            } else {
                echo '<p>No communication yet.</p>';
            }
            ?>
        </div>
    </div>

    <style>
        .crm-lead-detail { max-width:900px; margin:auto; font-family:Arial, sans-serif; }
        .crm-title { font-size:24px; margin-bottom:20px; }
        .crm-sub { font-size:16px; color:#555; }
        .crm-card { background:#fff; padding:15px 20px; border:1px solid #ddd; border-radius:8px; margin-bottom:20px; box-shadow:0 2px 5px rgba(0,0,0,0.05); }
        .crm-card h3 { margin-bottom:10px; color:#0149ad; }
        .crm-input { width:100%; padding:8px; margin:8px 0; border:1px solid #ccc; border-radius:5px; }
        .crm-button { background:#0149ad; color:#fff; padding:8px 16px; border:none; border-radius:6px; cursor:pointer; font-weight:bold; }
        .crm-button:hover { background:#01357f; }
        .crm-success { background:#e6ffed; border:1px solid #00a651; padding:8px; border-radius:6px; margin:10px 0; }
        .status-badge { background:#f0f0f0; padding:3px 8px; border-radius:5px; font-weight:bold; }
        .followup-badge { background:#fffae6; padding:2px 6px; border-radius:4px; color:#7a5d00; font-size:12px; margin-left:6px; }
        .crm-logs li { padding:6px 0; border-bottom:1px solid #eee; }
    </style>

    <script>
    (function(){
        var select = document.querySelector('select[name="lead_status"]');
        var wrapper = document.getElementById('lost-reason-wrapper');
        if (!select) return;
        select.addEventListener('change', function(){
            if (this.value === 'Lost Sale') wrapper.style.display = '';
            else wrapper.style.display = 'none';
        });
    })();
    </script>
    <?php
    return ob_get_clean();
}
add_shortcode('lead_detail','bestserve_crm_lead_detail');
