<?php
/**
 * WrenchPress dashboard: the live shop-snapshot landing page (D-02).
 *
 * Rendered as the default item under the single WrenchPress parent menu. Shows
 * open work orders broken down by status (each count clicks through to the
 * filtered Work Orders list), the new-leads / customers / vehicles totals,
 * quick-create buttons, and a collapsible getting-started checklist.
 *
 * Read-only and gated by VIEW_CUSTOMERS, the all-staff capability, so every
 * staff role (including the mechanic) lands here. Every echoed value is escaped
 * at the output boundary (T-03-06, T-03-07); the status slugs placed in the
 * Work Orders links are column data the list re-validates downstream, never
 * trusted on arrival.
 *
 * @package WrenchPress
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class WrenchPress_Dashboard_Page
 */
class WrenchPress_Dashboard_Page {

	/**
	 * Render the dashboard. Gated by the all-staff view capability.
	 *
	 * @return void
	 */
	public static function render() {
		if ( ! current_user_can( WrenchPress_Capabilities::VIEW_CUSTOMERS ) ) {
			wp_die( esc_html__( 'You do not have permission to do that.', 'pitdesk-repair-crm' ) );
		}

		$statuses = WrenchPress_Work_Orders_Repository::statuses();
		$counts   = WrenchPress_Work_Orders_Repository::counts_by_status();

		echo '<div class="wrap">';
		echo '<h1>' . esc_html__( 'PitDesk Auto Repair CRM', 'pitdesk-repair-crm' ) . '</h1>';

		self::render_quick_create();
		self::render_status_snapshot( $statuses, $counts );
		self::render_today_appointments();
		self::render_summary_counts();
		self::render_getting_started();

		echo '</div>';
	}

	/**
	 * Render the quick-create buttons for the three core records.
	 *
	 * @return void
	 */
	private static function render_quick_create() {
		$links = array(
			'wrenchpress-work-orders' => __( 'New work order', 'pitdesk-repair-crm' ),
			'wrenchpress-customers'   => __( 'New customer', 'pitdesk-repair-crm' ),
			'wrenchpress-vehicles'    => __( 'New vehicle', 'pitdesk-repair-crm' ),
		);

		echo '<p class="wrenchpress-quick-actions">';

		foreach ( $links as $page => $label ) {
			$url = add_query_arg(
				array(
					'page'   => $page,
					'action' => 'add',
				),
				admin_url( 'admin.php' )
			);

			echo '<a href="' . esc_url( $url ) . '" class="button button-primary">' . esc_html( $label ) . '</a> ';
		}

		echo '</p>';
	}

	/**
	 * Render the per-status work-order snapshot. Each status renders as a badge
	 * carrying its slug class, and the count is an anchor into the filtered Work
	 * Orders list.
	 *
	 * @param array<string,string> $statuses Status slug => label.
	 * @param array<string,int>    $counts   Status slug => count (plus 'all').
	 * @return void
	 */
	private static function render_status_snapshot( array $statuses, array $counts ) {
		echo '<h2>' . esc_html__( 'Open work orders by status', 'pitdesk-repair-crm' ) . '</h2>';
		echo '<ul class="wrenchpress-status-list">';

		foreach ( $statuses as $slug => $label ) {
			$count = isset( $counts[ $slug ] ) ? (int) $counts[ $slug ] : 0;

			$url = add_query_arg(
				array(
					'page'   => 'wrenchpress-work-orders',
					'status' => $slug,
				),
				admin_url( 'admin.php' )
			);

			$badge_class = 'wrenchpress-status wrenchpress-status--' . $slug;

			echo '<li>';
			echo '<a href="' . esc_url( $url ) . '">';
			echo '<span class="' . esc_attr( $badge_class ) . '">' . esc_html( $label ) . '</span> ';
			echo '<span class="wrenchpress-status-count">' . esc_html( (string) $count ) . '</span>';
			echo '</a>';
			echo '</li>';
		}

		echo '</ul>';
	}

	/**
	 * Render the "Today's appointments" snapshot (D-12). Lists today's
	 * appointments in ascending start-time order; each row shows the start time,
	 * the status badge (reusing the four appointment classes), and
	 * "{customer} - {vehicle}" as a link that opens the appointment in the
	 * calendar. Empty when there is nothing scheduled today.
	 *
	 * The snapshot is visible to every staff role (VIEW_APPOINTMENTS, already
	 * satisfied by the dashboard's all-staff view gate). Every echoed value is
	 * escaped at the output boundary (T-04-19); the deep-link date is the leading
	 * Y-m-d of the naive site-local start_at, sliced without a timezone
	 * conversion so it never shifts the calendar day.
	 *
	 * @return void
	 */
	private static function render_today_appointments() {
		$rows     = WrenchPress_Appointments_Repository::list_for_day( current_time( 'Y-m-d' ) );
		$statuses = WrenchPress_Appointments_Repository::statuses();

		echo '<h2>' . esc_html__( "Today's appointments", 'pitdesk-repair-crm' ) . '</h2>';

		if ( empty( $rows ) ) {
			echo '<p>' . esc_html__( 'No appointments scheduled for today.', 'pitdesk-repair-crm' ) . '</p>';
			return;
		}

		echo '<ul class="wrenchpress-status-list">';

		foreach ( $rows as $row ) {
			$customer      = WrenchPress_Customers_Repository::get( (int) $row->customer_id );
			$vehicle       = WrenchPress_Vehicles_Repository::get( (int) $row->vehicle_id );
			$customer_name = $customer ? trim( sprintf( '%s, %s', $customer->last_name, $customer->first_name ), ', ' ) : '';
			$vehicle_label = $vehicle ? WrenchPress_Vehicles_List_Table::vehicle_label( $vehicle ) : '';
			$entity_label  = trim( $customer_name . ' - ' . $vehicle_label, ' -' );

			$status       = (string) $row->status;
			$status_label = isset( $statuses[ $status ] ) ? $statuses[ $status ] : $status;
			$badge_class  = 'wrenchpress-status wrenchpress-status--' . $status;

			$start_time = date_i18n( get_option( 'time_format' ), strtotime( (string) $row->start_at ) );

			$url = add_query_arg(
				array(
					'page'        => 'wrenchpress-appointments',
					'appointment' => (int) $row->id,
					'date'        => substr( (string) $row->start_at, 0, 10 ),
				),
				admin_url( 'admin.php' )
			);

			echo '<li>';
			echo '<a href="' . esc_url( $url ) . '">';
			echo '<span class="wrenchpress-appointment-time">' . esc_html( $start_time ) . '</span> ';
			echo '<span class="' . esc_attr( $badge_class ) . '">' . esc_html( $status_label ) . '</span> ';
			echo '<span class="wrenchpress-appointment-entity">' . esc_html( $entity_label ) . '</span>';
			echo '</a>';
			echo '</li>';
		}

		echo '</ul>';
	}

	/**
	 * Render the lead / customer / vehicle summary counts.
	 *
	 * @return void
	 */
	private static function render_summary_counts() {
		$new_leads = (int) WrenchPress_Leads_Repository::count_by_status( 'new' );
		$customers = (int) WrenchPress_Customers_Repository::count_active();
		$vehicles  = (int) WrenchPress_Vehicles_Repository::count_active();

		$leads_url = add_query_arg( array( 'page' => 'wrenchpress-leads' ), admin_url( 'admin.php' ) );
		$cust_url  = add_query_arg( array( 'page' => 'wrenchpress-customers' ), admin_url( 'admin.php' ) );

		echo '<h2>' . esc_html__( 'Snapshot', 'pitdesk-repair-crm' ) . '</h2>';
		echo '<ul class="wrenchpress-summary-list">';

		echo '<li><a href="' . esc_url( $leads_url ) . '">' . esc_html__( 'New leads', 'pitdesk-repair-crm' ) . ': ' . esc_html( (string) $new_leads ) . '</a></li>';
		echo '<li><a href="' . esc_url( $cust_url ) . '">' . esc_html__( 'Customers', 'pitdesk-repair-crm' ) . ': ' . esc_html( (string) $customers ) . '</a></li>';
		echo '<li>' . esc_html__( 'Vehicles', 'pitdesk-repair-crm' ) . ': ' . esc_html( (string) $vehicles ) . '</li>';

		echo '</ul>';
	}

	/**
	 * Render the collapsible getting-started guide using a native details
	 * element so no JavaScript is required. Covers the core staff flow and the
	 * ways the public visit form can be embedded on the site.
	 *
	 * @return void
	 */
	private static function render_getting_started() {
		$flow = array(
			__( 'A customer submits the visit form on your site. It lands as a new lead.', 'pitdesk-repair-crm' ),
			__( 'Promote the lead to a customer, then add their vehicle.', 'pitdesk-repair-crm' ),
			__( 'Create a work order and move it through the statuses as the job progresses.', 'pitdesk-repair-crm' ),
			__( 'Add line items and notes; the vehicle keeps a full service history.', 'pitdesk-repair-crm' ),
		);

		$embeds = array(
			__( 'Shortcode: paste [wrenchpress_visit_form] into any page, post, or builder text area.', 'pitdesk-repair-crm' ),
			__( 'Block editor: add the "Visit request form" block.', 'pitdesk-repair-crm' ),
			__( 'Elementor: drop in the "PitDesk Visit Form" widget.', 'pitdesk-repair-crm' ),
			__( 'Divi: use the "PitDesk Visit Form" module.', 'pitdesk-repair-crm' ),
		);

		echo '<details class="wrenchpress-getting-started">';
		echo '<summary>' . esc_html__( 'Getting started', 'pitdesk-repair-crm' ) . '</summary>';

		echo '<h3>' . esc_html__( 'How PitDesk works', 'pitdesk-repair-crm' ) . '</h3>';
		echo '<ol>';
		foreach ( $flow as $step ) {
			echo '<li>' . esc_html( $step ) . '</li>';
		}
		echo '</ol>';

		echo '<h3>' . esc_html__( 'Place the visit form on your site', 'pitdesk-repair-crm' ) . '</h3>';
		echo '<p>' . esc_html__( 'The form adopts your theme or builder styling. Use whichever tool your site is built with:', 'pitdesk-repair-crm' ) . '</p>';
		echo '<ul>';
		foreach ( $embeds as $embed ) {
			echo '<li>' . esc_html( $embed ) . '</li>';
		}
		echo '</ul>';

		echo '</details>';
	}
}
