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

class Catalog extends CI_Controller
{
	private $catalog_config;

	public function __construct()
	{
		parent::__construct();
		$this->load->model('Catalog_model', 'catalog');
		$this->load->helper('url');
		$this->load->library('session');
		$this->load->config('catalog');
		$this->catalog_config = array(
			'catalog_name' => $this->config->item('catalog_name'),
			'catalog_default_employee_id' => $this->config->item('catalog_default_employee_id'),
			'catalog_default_location_id' => $this->config->item('catalog_default_location_id'),
			'catalog_token_bytes' => $this->config->item('catalog_token_bytes'),
			'catalog_currency_symbol' => $this->config->item('catalog_currency_symbol')
		);
		$this->catalog->ensure_schema();
	}

	public function view($token)
	{
		$link = $this->catalog->get_link_by_token($token);
		if (!$link)
		{
			if ($this->render_if_link_disabled($token))
			{
				return;
			}
			show_error('Link no encontrado o desactivado.', 404);
			return;
		}

		if (strtotime($link['expires_at']) < time())
		{
			$this->render_link_unavailable($link, 'Link expirado');
			return;
		}

		$location_id = !empty($link['location_id'])
			? (int) $link['location_id']
			: (int) $this->catalog_config['catalog_default_location_id'];
		$products = $this->catalog->get_products_for_link($link, $location_id);
		$categories = array();
		foreach ($products as $product)
		{
			$cid = !empty($product['category_id']) ? (int) $product['category_id'] : 0;
			$cname = trim((string) $product['category_name']);
			if ($cid <= 0 || $cname === '')
			{
				continue;
			}
			$categories[$cid] = $cname;
		}
		asort($categories);

		$draft = $this->session->userdata($this->draft_key($token));
		$draft_quantities = array();
		$draft_note = '';
		$can_order = (int) $link['customer_id'] > 0;
		if (is_array($draft))
		{
			$draft_quantities = !empty($draft['quantities']) && is_array($draft['quantities']) ? $draft['quantities'] : array();
			$draft_note = !empty($draft['note']) ? (string) $draft['note'] : '';
		}

		$data = array(
			'catalog_name' => $this->catalog_config['catalog_name'],
			'currency_symbol' => $this->catalog_config['catalog_currency_symbol'],
			'link' => $link,
			'products' => $products,
			'categories' => $categories,
			'catalog_announcement' => $this->catalog->get_setting('catalog_announcement', ''),
			'checkout_terms' => $this->catalog->get_setting('checkout_terms', ''),
			'template' => $this->catalog->get_active_template(),
			'logo_file_id' => $this->catalog->get_company_logo_file_id($location_id),
			'draft_quantities' => $draft_quantities,
			'draft_note' => $draft_note,
			'can_order' => $can_order
		);

		$this->load->view('catalog/public_catalog', $data);
	}

	public function checkout($token)
	{
		$link = $this->catalog->get_link_by_token($token);
		if (!$link)
		{
			if ($this->render_if_link_disabled($token))
			{
				return;
			}
			show_error('Link no encontrado o desactivado.', 404);
			return;
		}

		if (strtotime($link['expires_at']) < time())
		{
			$this->render_link_unavailable($link, 'Link expirado');
			return;
		}
		if ((int) $link['customer_id'] <= 0)
		{
			show_error('Este link es solo para ver catalogo. No permite comprar.', 403);
			return;
		}

		$location_id = !empty($link['location_id'])
			? (int) $link['location_id']
			: (int) $this->catalog_config['catalog_default_location_id'];
		$products = $this->catalog->get_products_for_link($link, $location_id);
		$products_map = array();
		foreach ($products as $product)
		{
			$products_map[(int) $product['item_id']] = $product;
		}

		$quantities = $this->input->post('qty');
		if (!is_array($quantities))
		{
			show_error('No se enviaron productos.', 400);
			return;
		}

		$cart_rows = array();
		$selected_quantities = array();
		foreach ($quantities as $item_id => $qty_raw)
		{
			$item_id = (int) $item_id;
			$qty = (float) $qty_raw;
			if ($qty <= 0)
			{
				continue;
			}

			if (!isset($products_map[$item_id]))
			{
				continue;
			}

			$product = $products_map[$item_id];
			$line_total = $qty * (float) $product['final_price'];
			$selected_quantities[$item_id] = $qty;
			$cart_rows[] = array(
				'item_id' => $item_id,
				'item_name' => $product['name'],
				'quantity' => $qty,
				'unit_price' => (float) $product['final_price'],
				'line_total' => $line_total,
				'cost_price' => (float) $product['cost_price'],
				'image_id' => $product['image_id']
			);
		}

		if (count($cart_rows) === 0)
		{
			show_error('Debes seleccionar al menos un producto.', 400);
			return;
		}

		$note = trim((string) $this->input->post('customer_note'));
		$checkout_terms = trim((string) $this->catalog->get_setting('checkout_terms', ''));
		if ($checkout_terms !== '')
		{
			$accepted_terms = (int) $this->input->post('terms_accepted') === 1;
			if (!$accepted_terms)
			{
				show_error('Debes aceptar los terminos y condiciones para continuar.', 400);
				return;
			}
		}

		$this->session->set_userdata($this->draft_key($token), array(
			'quantities' => $selected_quantities,
			'note' => $note,
			'items' => $cart_rows,
			'created_at' => time()
		));

		$data = array(
			'catalog_name' => $this->catalog_config['catalog_name'],
			'currency_symbol' => $this->catalog_config['catalog_currency_symbol'],
			'link' => $link,
			'items' => $cart_rows,
			'note' => $note
		);

		$this->load->view('catalog/order_review', $data);
	}

	public function confirm($token)
	{
		$link = $this->catalog->get_link_by_token($token);
		if (!$link)
		{
			if ($this->render_if_link_disabled($token))
			{
				return;
			}
			show_error('Link no encontrado o desactivado.', 404);
			return;
		}

		if (strtotime($link['expires_at']) < time())
		{
			$this->render_link_unavailable($link, 'Link expirado');
			return;
		}
		if ((int) $link['customer_id'] <= 0)
		{
			show_error('Este link es solo para ver catalogo. No permite comprar.', 403);
			return;
		}

		$draft = $this->session->userdata($this->draft_key($token));
		if (!is_array($draft) || empty($draft['items']) || !is_array($draft['items']))
		{
			show_error('No hay un pedido pendiente para confirmar.', 400);
			return;
		}

		$cart_rows = $draft['items'];
		$note = !empty($draft['note']) ? (string) $draft['note'] : '';

		$create = $this->catalog->create_order($link, $cart_rows, $note, array(
			'employee_id' => (int) $this->catalog_config['catalog_default_employee_id'],
			'location_id' => (int) $this->catalog_config['catalog_default_location_id']
		));

		if (!$create['ok'])
		{
			show_error($create['message'], 500);
			return;
		}

		$this->catalog->make_link_public((int) $link['id']);

		$this->session->unset_userdata($this->draft_key($token));

		redirect('catalog/l/' . rawurlencode($token) . '/thanks/' . (int) $create['order_id']);
	}

	public function thanks($token, $order_id)
	{
		$link = $this->catalog->get_link_by_token($token);
		if (!$link)
		{
			if ($this->render_if_link_disabled($token))
			{
				return;
			}
			show_error('Link no encontrado o desactivado.', 404);
			return;
		}

		$order = $this->catalog->get_order((int) $order_id);
		if (!$order || $order['token'] !== $token)
		{
			show_404();
			return;
		}

		$location_id = !empty($link['location_id'])
			? (int) $link['location_id']
			: (int) $this->catalog_config['catalog_default_location_id'];
		$thanks_message = $this->catalog->get_setting('thank_you_message', 'Gracias por su pedido. Pronto nos comunicaremos con usted.');

		$data = array(
			'catalog_name' => $this->catalog_config['catalog_name'],
			'currency_symbol' => $this->catalog_config['catalog_currency_symbol'],
			'link' => $link,
			'order' => $order,
			'items' => $this->catalog->get_order_items((int) $order_id),
			'thanks_message' => $thanks_message,
			'logo_file_id' => $this->catalog->get_company_logo_file_id($location_id)
		);

		$this->load->view('catalog/order_thanks', $data);
	}

	public function download_receipt($token, $order_id)
	{
		$link = $this->catalog->get_link_by_token($token);
		if (!$link)
		{
			if ($this->render_if_link_disabled($token))
			{
				return;
			}
			show_error('Link no encontrado o desactivado.', 404);
			return;
		}

		$order = $this->catalog->get_order((int) $order_id);
		if (!$order || $order['token'] !== $token)
		{
			show_404();
			return;
		}

		$this->load->library('m_pdf');
		$items = $this->catalog->get_order_items((int) $order_id);
		$currency = (string) $this->catalog_config['catalog_currency_symbol'];
		$receipt_no = 'REC-' . str_pad((string) (int) $order['id'], 6, '0', STR_PAD_LEFT);
		$logo_data_uri = '';

		$location_id = !empty($link['location_id'])
			? (int) $link['location_id']
			: (int) $this->catalog_config['catalog_default_location_id'];
		$logo_file_id = $this->catalog->get_company_logo_file_id($location_id);
		if (!empty($logo_file_id))
		{
			$logo = $this->catalog->get_image_file((int) $logo_file_id);
			if ($logo && !empty($logo['file_data']))
			{
				$mime = 'image/jpeg';
				$file_name = strtolower((string) $logo['file_name']);
				if (preg_match('/\.png$/', $file_name))
				{
					$mime = 'image/png';
				}
				elseif (preg_match('/\.gif$/', $file_name))
				{
					$mime = 'image/gif';
				}
				elseif (preg_match('/\.webp$/', $file_name))
				{
					$mime = 'image/webp';
				}

				$logo_data_uri = 'data:' . $mime . ';base64,' . base64_encode($logo['file_data']);
			}
		}

		$rows_html = '';
		foreach ($items as $item)
		{
			$rows_html .= '<tr>'
				. '<td>' . htmlspecialchars((string) $item['item_name'], ENT_QUOTES, 'UTF-8') . '</td>'
				. '<td class="text-right">' . number_format((float) $item['quantity'], 2) . '</td>'
				. '<td class="text-right">' . $currency . number_format((float) $item['unit_price'], 2) . '</td>'
				. '<td class="text-right strong">' . $currency . number_format((float) $item['line_total'], 2) . '</td>'
				. '</tr>';
		}

		$note_html = '';
		if (trim((string) $order['customer_note']) !== '')
		{
			$note_html = '<div class="note"><span class="label">Nota:</span> '
				. nl2br(htmlspecialchars((string) $order['customer_note'], ENT_QUOTES, 'UTF-8'))
				. '</div>';
		}

		$logo_html = '';
		if ($logo_data_uri !== '')
		{
			$logo_html = '<img class="logo" src="' . $logo_data_uri . '" alt="Logo">';
		}

		$html = '
		<!doctype html>
		<html>
		<head>
			<meta charset="utf-8">
			<style>
				body { font-family: DejaVu Sans, sans-serif; color:#0f172a; font-size:12px; }
				.sheet { border:1px solid #e2e8f0; border-radius:10px; padding:18px; }
				.head { display:table; width:100%; margin-bottom:14px; }
				.head-left, .head-right { display:table-cell; vertical-align:top; }
				.head-right { text-align:right; }
				.logo { width:130px; max-height:62px; object-fit:contain; }
				.title { font-size:22px; font-weight:700; color:#0f766e; margin:6px 0 4px; }
				.muted { color:#64748b; }
				.badge { display:inline-block; padding:4px 8px; background:#eef2ff; border:1px solid #c7d2fe; border-radius:16px; font-size:11px; }
				.meta { margin:10px 0 14px; }
				.meta-row { margin:2px 0; }
				table { width:100%; border-collapse:collapse; }
				th { text-align:left; background:#f8fafc; color:#475569; font-size:11px; border-bottom:1px solid #cbd5e1; padding:8px; }
				td { border-bottom:1px solid #e2e8f0; padding:8px; }
				.text-right { text-align:right; }
				.strong { font-weight:700; }
				.summary { width:300px; margin-left:auto; margin-top:10px; }
				.summary td { border:none; padding:4px 0; }
				.summary .total { border-top:1px solid #cbd5e1; padding-top:8px; font-size:14px; font-weight:700; }
				.note { margin-top:14px; background:#fffbeb; border:1px solid #fde68a; border-radius:8px; padding:10px; }
				.label { font-weight:700; }
				.footer { margin-top:14px; text-align:center; color:#475569; font-size:11px; }
			</style>
		</head>
		<body>
			<div class="sheet">
				<div class="head">
					<div class="head-left">
						' . $logo_html . '
						<div class="title">RECIBO DE PEDIDO</div>
						<div class="muted">Comprobante de compra</div>
					</div>
					<div class="head-right">
						<div class="badge">Recibo ' . htmlspecialchars($receipt_no, ENT_QUOTES, 'UTF-8') . '</div>
					</div>
				</div>

				<div class="meta">
					<div class="meta-row"><span class="label">Pedido:</span> #' . (int) $order['id'] . '</div>
					<div class="meta-row"><span class="label">Cliente:</span> ' . htmlspecialchars((string) $order['customer_name'], ENT_QUOTES, 'UTF-8') . '</div>
					<div class="meta-row"><span class="label">Fecha:</span> ' . htmlspecialchars((string) $order['ordered_at'], ENT_QUOTES, 'UTF-8') . '</div>
				</div>

				<table>
					<thead>
						<tr>
							<th style="width:52%;">Producto</th>
							<th style="width:16%;" class="text-right">Cantidad</th>
							<th style="width:16%;" class="text-right">Precio</th>
							<th style="width:16%;" class="text-right">Total</th>
						</tr>
					</thead>
					<tbody>' . $rows_html . '</tbody>
				</table>

				<table class="summary">
					<tr><td>Subtotal</td><td class="text-right">' . $currency . number_format((float) $order['subtotal'], 2) . '</td></tr>
					<tr><td>Impuesto</td><td class="text-right">' . $currency . number_format((float) $order['tax'], 2) . '</td></tr>
					<tr class="total"><td>TOTAL</td><td class="text-right">' . $currency . number_format((float) $order['total'], 2) . '</td></tr>
				</table>

				' . $note_html . '
				<div class="footer">Gracias por su compra</div>
			</div>
		</body>
		</html>';

		$this->m_pdf->generate_pdf($html, TRUE, 'pedido_' . (int) $order['id'] . '.pdf');
	}

	public function image($file_id)
	{
		$file = $this->catalog->get_image_file((int) $file_id);
		if (!$file)
		{
			show_404();
			return;
		}

		$filename = strtolower((string) $file['file_name']);
		$content_type = 'application/octet-stream';
		if (preg_match('/\.(jpe?g)$/', $filename))
		{
			$content_type = 'image/jpeg';
		}
		elseif (preg_match('/\.(png)$/', $filename))
		{
			$content_type = 'image/png';
		}
		elseif (preg_match('/\.(gif)$/', $filename))
		{
			$content_type = 'image/gif';
		}
		elseif (preg_match('/\.(webp)$/', $filename))
		{
			$content_type = 'image/webp';
		}

		$this->output
			->set_content_type($content_type)
			->set_output($file['file_data']);
	}

	private function draft_key($token)
	{
		return 'catalog_draft_' . sha1((string) $token);
	}

	private function render_if_link_disabled($token)
	{
		$link_any = $this->catalog->get_link_by_token_any((string) $token);
		if (!$link_any)
		{
			return FALSE;
		}

		if ((int) $link_any['status'] === 1)
		{
			return FALSE;
		}

		$location_id = !empty($link_any['location_id'])
			? (int) $link_any['location_id']
			: (int) $this->catalog_config['catalog_default_location_id'];

		$data = array(
			'catalog_name' => $this->catalog_config['catalog_name'],
			'logo_file_id' => $this->catalog->get_company_logo_file_id($location_id),
			'message' => $this->catalog->get_setting('disabled_link_message', 'Este link fue desactivado por la empresa. Si necesitas ayuda, comunicate con nuestro equipo.'),
			'title' => 'Link desactivado',
			'public_catalog_url' => $this->resolve_public_catalog_url()
		);

		$this->output->set_status_header(410);
		$this->load->view('catalog/link_disabled', $data);
		return TRUE;
	}

	private function render_link_unavailable($link, $title)
	{
		$location_id = !empty($link['location_id'])
			? (int) $link['location_id']
			: (int) $this->catalog_config['catalog_default_location_id'];

		$data = array(
			'catalog_name' => $this->catalog_config['catalog_name'],
			'logo_file_id' => $this->catalog->get_company_logo_file_id($location_id),
			'message' => $this->catalog->get_setting('disabled_link_message', 'Este link fue desactivado por la empresa. Si necesitas ayuda, comunicate con nuestro equipo.'),
			'title' => (string) $title,
			'public_catalog_url' => $this->resolve_public_catalog_url()
		);

		$this->output->set_status_header(410);
		$this->load->view('catalog/link_disabled', $data);
	}

	private function resolve_public_catalog_url()
	{
		$public_link = $this->catalog->get_latest_active_public_link();
		if ($public_link && !empty($public_link['token']))
		{
			return site_url('catalog/l/' . rawurlencode((string) $public_link['token']));
		}

		return '';
	}
}
