/* 
Theme Name: Primarycare Medicine
Theme URI: https://github.com/elementor/hello-theme-child/
Description: Primarycare Medicine is a child theme of Hello Elementor, created by Elementor team
Author: Elementor Team
Author URI: https://elementor.com/
Template: hello-elementor
Version: 2.0.0
Text Domain: hello-elementor-child
License: GNU General Public License v3 or later.
License URI: https://www.gnu.org/licenses/gpl-3.0.html
Tags: flexible-header, custom-colors, custom-menu, custom-logo, editor-style, featured-images, rtl-language-support, threaded-comments, translation-ready
*/

/* Add your custom styles here */

function restrict_contributor_publishing() {
    $role = get_role('contributor');
    if ($role) {
        $role->remove_cap('publish_posts');
    }
}
add_action('init', 'restrict_contributor_publishing');

function notify_editors_on_pending($new_status, $old_status, $post) {
    if ($new_status == 'pending' && $post->post_type == 'post') {

        // Get all editors
        $editors = get_users([
            'role' => 'editor',
        ]);

        $emails = [];
        foreach ($editors as $editor) {
            $emails[] = $editor->user_email;
        }

        // Add admin email too
        $emails[] = get_option('admin_email');

        $subject = 'New Post Submitted for Review';
        $message = 'A new post "' . $post->post_title . '" is awaiting review: ' . get_edit_post_link($post->ID);

        wp_mail($emails, $subject, $message);
    }
}
add_action('transition_post_status', 'notify_editors_on_pending', 10, 3);

function add_feedback_metabox() {
    add_meta_box(
        'editor_feedback',
        'Editorial Feedback',
        'render_feedback_metabox',
        'post',
        'side'
    );
}
add_action('add_meta_boxes', 'add_feedback_metabox');

function render_feedback_metabox($post) {
    if (!current_user_can('edit_others_posts')) return;

    $feedback = get_post_meta($post->ID, '_editor_feedback', true);

    echo '<textarea style="width:100%;height:100px;" name="editor_feedback">' . esc_textarea($feedback) . '</textarea>';
}

function save_editor_feedback($post_id) {
    if (isset($_POST['editor_feedback'])) {
        update_post_meta($post_id, '_editor_feedback', sanitize_textarea_field($_POST['editor_feedback']));
    }
}
add_action('save_post', 'save_editor_feedback');

function notify_author_on_draft($new_status, $old_status, $post) {
    if ($new_status == 'draft' && $old_status == 'pending') {

        $author = get_user_by('id', $post->post_author);
        $feedback = get_post_meta($post->ID, '_editor_feedback', true);

        $subject = 'Your post needs changes';
        $message = 'Your post "' . $post->post_title . '" يحتاج تعديل.\n\nFeedback:\n' . $feedback . '\n\nEdit here: ' . get_edit_post_link($post->ID);

        wp_mail($author->user_email, $subject, $message);
    }
}
add_action('transition_post_status', 'notify_author_on_draft', 10, 3);