<?php
/** Inquiries -> Gravity Forms. Creates the form (idempotent by title) and
 *  imports inquiries as entries. Skips import if the form already has entries. */
if ( ! defined('ABSPATH') ) { exit; }
if ( ! class_exists('GFAPI') ) { echo "GFAPI not available\n"; return; }

$FORM_TITLE = 'Admissions Inquiries (migrated)';

// Field map: id => [type,label]. Order matters for display.
$fields = array(
	1  => array('text',     'Name'),
	2  => array('email',    'Email'),
	3  => array('phone',    'Phone'),
	4  => array('text',     'Type'),
	5  => array('text',     'Secondary Name'),
	6  => array('text',     'Target Grade'),
	7  => array('text',     'Target Year'),
	8  => array('text',     'Student Type'),
	9  => array('textarea', 'Question'),
	10 => array('text',     'Location'),
	11 => array('text',     'Archived (migrated flag)'),
);

// --- find or create the form ---
$form_id = 0;
foreach ( GFAPI::get_forms() as $f ) { if ( $f['title'] === $FORM_TITLE ) { $form_id = $f['id']; break; } }

if ( ! $form_id ) {
	$gf_fields = array();
	foreach ( $fields as $id => $meta ) {
		$gf_fields[] = array( 'id' => $id, 'type' => $meta[0], 'label' => $meta[1] );
	}
	$form = array(
		'title'       => $FORM_TITLE,
		'description' => 'Imported from the Laravel CMS admissions inquiries. Date Submitted is the entry date; "Archived" preserves the original archived flag.',
		'fields'      => $gf_fields,
	);
	$form_id = GFAPI::add_form( $form );
	if ( is_wp_error($form_id) ) { echo "form create failed: ".$form_id->get_error_message()."\n"; return; }
	echo "Created form #$form_id\n";
} else {
	echo "Form #$form_id already exists\n";
}

// --- guard: don't double-import ---
$existing = GFAPI::count_entries( $form_id, array( 'status' => 'active' ) )
          + GFAPI::count_entries( $form_id, array( 'status' => 'trash' ) );
if ( $existing > 0 ) { echo "Form already has $existing entries — skipping import.\n"; return; }

$rows = json_decode( file_get_contents( WP_CONTENT_DIR . '/_import/inquiries.json' ), true );
$ok=0; $fail=0;
foreach ( $rows as $r ) {
	$entry = array(
		'form_id'    => $form_id,
		'1'  => $r['name'], '2' => $r['email'], '3' => $r['phone'], '4' => $r['type'],
		'5'  => $r['secondary'], '6' => $r['grade'], '7' => $r['year'], '8' => $r['studenttype'],
		'9'  => $r['question'], '10' => $r['location'],
		'11' => $r['archived'] ? 'yes' : 'no',
		'is_read'    => $r['archived'] ? 1 : 0,   // archived -> read; the 12 open ones stay unread/bold
	);
	if ( ! empty($r['date']) ) { $entry['date_created'] = $r['date']; }
	$res = GFAPI::add_entry( $entry );
	if ( is_wp_error($res) ) { $fail++; } else { $ok++; }
}
echo "INQUIRIES: form=$form_id imported=$ok failed=$fail\n";
