<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Apply — talent network applications and brand collaboration inquiries.
 */
#[\AllowDynamicProperties]
class Apply extends Public_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model(array('application_model', 'inquiry_model'));
	}

	/* ====================================================================
	 * TALENT APPLICATION
	 * ================================================================= */

	/** Talent application form. */
	public function talent()
	{
		$this->meta(array(
			'title'       => 'Join the Talent Network — Bloom Iris Agency',
			'description' => 'Apply to join the Bloom Iris talent roster.',
		));
		$this->render('apply/talent', array(
			'categories' => $this->config->item('talent_categories'),
		));
	}

	/** Handle talent application submission. */
	public function talent_submit()
	{
		$this->load->library('form_validation');
		$this->form_validation->set_rules('name', 'Name', 'required|trim|max_length[140]');
		$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');
		$this->form_validation->set_rules('phone', 'Phone', 'required|trim');
		$this->form_validation->set_rules('category', 'Category', 'required');
		$this->form_validation->set_rules('bio', 'About You', 'required|trim');

		if ($this->form_validation->run() === FALSE)
		{
			$this->session->set_flashdata('error', strip_tags(validation_errors()) ?: 'Please complete all required fields.');
			redirect('apply/talent');
		}
		if ($this->input->post('website')) redirect('apply/talent'); // honeypot

		// Optional photo upload.
		$photo = $this->_upload_photo('photo', 'applications');

		$id = $this->application_model->insert(array(
			'name'          => $this->input->post('name', TRUE),
			'email'         => $this->input->post('email', TRUE),
			'phone'         => $this->input->post('phone', TRUE),
			'category'      => $this->input->post('category', TRUE),
			'location'      => $this->input->post('location', TRUE),
			'instagram'     => $this->input->post('instagram', TRUE),
			'followers'     => $this->input->post('followers', TRUE),
			'portfolio_url' => $this->input->post('portfolio_url', TRUE),
			'bio'           => $this->input->post('bio', TRUE),
			'photo'         => $photo,
			'status'        => 'pending',
			'ip_address'    => $this->input->ip_address(),
		));

		$this->load->library('mailer');
		$this->mailer->notify_admin(
			'New Talent Application — '.$this->input->post('name', TRUE),
			'New Talent Application',
			'<p><strong>'.html_escape($this->input->post('name', TRUE)).'</strong> applied as '
			.'<strong>'.html_escape($this->input->post('category', TRUE)).'</strong>.</p>'
			.'<p>Email: '.html_escape($this->input->post('email', TRUE)).'<br>'
			.'Phone: '.html_escape($this->input->post('phone', TRUE)).'</p>'
		);
		$this->mailer->send(
			$this->input->post('email', TRUE),
			'Your application was received — Bloom Iris Agency',
			'Thank you for applying',
			'<p>Hi '.html_escape($this->input->post('name', TRUE)).',</p>'
			.'<p>Thank you for applying to join the Bloom Iris talent network. '
			.'Our team reviews every application carefully and will be in touch if there\'s a fit.</p>'
			.'<p>Warm regards,<br>The Bloom Iris Team</p>'
		);

		$this->session->set_flashdata('success', 'Application submitted! We\'ll review it and be in touch.');
		redirect('apply/talent');
	}

	/* ====================================================================
	 * BRAND COLLABORATION INQUIRY
	 * ================================================================= */

	/** Brand collaboration form. */
	public function brand()
	{
		$this->meta(array(
			'title'       => 'Start a Brand Collaboration — Bloom Iris Agency',
			'description' => 'Partner with Bloom Iris Agency on your next campaign.',
		));
		$this->render('apply/brand', array(
			'services' => $this->service_model->active(),
		));
	}

	/** Handle brand inquiry submission. */
	public function brand_submit()
	{
		$this->load->library('form_validation');
		$this->form_validation->set_rules('name', 'Name', 'required|trim');
		$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');
		$this->form_validation->set_rules('company', 'Company', 'required|trim');
		$this->form_validation->set_rules('message', 'Project Details', 'required|trim');

		if ($this->form_validation->run() === FALSE)
		{
			$this->session->set_flashdata('error', strip_tags(validation_errors()) ?: 'Please complete all required fields.');
			redirect('apply/brand');
		}
		if ($this->input->post('website')) redirect('apply/brand'); // honeypot

		// Optional brief upload (PDF / image).
		$brief = $this->_upload_brief('brief', 'applications');

		$id = $this->inquiry_model->insert(array(
			'type'         => 'brand',
			'name'         => $this->input->post('name', TRUE),
			'email'        => $this->input->post('email', TRUE),
			'phone'        => $this->input->post('phone', TRUE),
			'company'      => $this->input->post('company', TRUE),
			'service_id'   => (int) $this->input->post('service_id') ?: NULL,
			'budget_range' => $this->input->post('budget_range', TRUE),
			'timeline'     => $this->input->post('timeline', TRUE),
			'subject'      => 'Brand Collaboration — '.$this->input->post('company', TRUE),
			'message'      => $this->input->post('message', TRUE),
			'brief_file'   => $brief,
			'status'       => 'new',
			'ip_address'   => $this->input->ip_address(),
		));

		$this->load->library('mailer');
		$this->mailer->notify_admin(
			'New Brand Collaboration — '.$this->input->post('company', TRUE),
			'New Brand Collaboration Inquiry',
			'<p><strong>'.html_escape($this->input->post('company', TRUE)).'</strong> '
			.'submitted a collaboration inquiry.</p>'
			.'<p>Contact: '.html_escape($this->input->post('name', TRUE)).' — '
			.html_escape($this->input->post('email', TRUE)).'</p>'
			.'<p>'.nl2br(html_escape($this->input->post('message', TRUE))).'</p>'
		);
		$this->mailer->send(
			$this->input->post('email', TRUE),
			'We received your collaboration inquiry — Bloom Iris Agency',
			'Thank you for reaching out',
			'<p>Hi '.html_escape($this->input->post('name', TRUE)).',</p>'
			.'<p>Thank you for considering Bloom Iris Agency as your creative partner. '
			.'We\'ve received your project details and will respond very soon.</p>'
			.'<p>Warm regards,<br>The Bloom Iris Team</p>'
		);

		$this->session->set_flashdata('success', 'Thank you! Your collaboration inquiry has been received.');
		redirect('apply/brand');
	}

	/* ====================================================================
	 * UPLOAD HELPERS
	 * ================================================================= */

	/** Upload an image; returns relative path or NULL. */
	private function _upload_photo($field, $subdir)
	{
		if (empty($_FILES[$field]['name'])) return NULL;

		$path = FCPATH.'assets/uploads/'.$subdir.'/';
		$config = array(
			'upload_path'   => $path,
			'allowed_types' => $this->config->item('allowed_images') ?: 'jpg|jpeg|png|webp',
			'max_size'      => $this->config->item('upload_max_size') ?: 8192,
			'file_name'     => 'talent-'.time().'-'.bin2hex(random_bytes(3)),
			'encrypt_name'  => FALSE,
		);
		$this->load->library('upload', $config);

		if ($this->upload->do_upload($field))
		{
			$data = $this->upload->data();
			return $subdir.'/'.$data['file_name'];
		}
		return NULL;
	}

	/** Upload a brief (PDF or image); returns relative path or NULL. */
	private function _upload_brief($field, $subdir)
	{
		if (empty($_FILES[$field]['name'])) return NULL;

		$path = FCPATH.'assets/uploads/'.$subdir.'/';
		$config = array(
			'upload_path'   => $path,
			'allowed_types' => $this->config->item('allowed_docs') ?: 'pdf|jpg|jpeg|png',
			'max_size'      => $this->config->item('upload_max_size') ?: 8192,
			'file_name'     => 'brief-'.time().'-'.bin2hex(random_bytes(3)),
			'encrypt_name'  => FALSE,
		);
		$this->load->library('upload', $config);

		if ($this->upload->do_upload($field))
		{
			$data = $this->upload->data();
			return $subdir.'/'.$data['file_name'];
		}
		return NULL;
	}
}
