<?php
defined('COT_CODE') or die('Wrong URL');

$return['success'] = false;
$return['redirect'] = '';
$return['error'] = 'Произошла ошибка. Перезагружите страницу.';

$wantId = cot_import('wantId', 'P', 'INT');
if($usr['id'] > 0) {
  $return['error'] = 'Запрос данной услуги уже не актуален или не найден';
  if($wantId > 0) {
    require_once cot_incfile('projects', 'module');
    $item = $db->query("SELECT p.*, u.* FROM $db_projects AS p LEFT JOIN $db_users AS u ON u.user_id=p.item_userid WHERE item_id=".$wantId.' AND item_state=0 LIMIT 1')->fetch();
    if($item['item_id'] > 0) {
      if(($item['item_update'] > 0 && $item['item_update'] < ($sys['now'] - 86400)) || ($item['item_update'] == 0 && $item['item_date'] < ($sys['now'] - 86400))) {
        $db->update($db_projects, array('item_state' => 1), 'item_id='.$item['item_id']);
      } else {
        $isoffer = $db->query("SELECT * FROM $db_projects_offers WHERE offer_pid=".$wantId.' AND offer_userid='.$usr['id'].' LIMIT 1')->fetch();
        if($isoffer['offer_id'] > 0) {
          $return['error'] = 'Вы уже отправили свое предложение по данному запросу';
        } else {
          require_once cot_incfile('market', 'module');

        	$roffer = array(
            'offer_pid' => $item['item_id'],
            'offer_date' => $sys['now'],
            'offer_userid' => $usr['id'],
            'offer_text' => cot_import('description', 'P', 'TXT'),
            'offer_json' => array(),
            'offer_choise' => '',
            'offer_view' => 0,
          );

          $roffer['offer_text'] = trim($roffer['offer_text']);
          if(empty($roffer['offer_text'])) {
            $return['error'] = 'Укажите комментарий для покупателя';
          } else {
            $offerType = cot_import('offerType', 'P', 'TXT');

            if($offerType == 'custom') { // Индивидульная услуга лайт версия
              $mdata = array(
                'type' => 'offer_custom_prd',
                'pid' => 0,
                'name' => cot_import('prd_name', 'P', 'TXT'),
                'desc' => cot_import('prd_desc', 'P', 'TXT'),
                'duration' => cot_import('prd_duration', 'P', 'INT'),
                'price' => cot_import('prd_price', 'P', 'NUM'),
                'count' => 1,
                'decline' => 0,
                'orderId' => 0
              );
              if(!$mdata['duration']) $mdata['duration'] = 0;
              if(!$mdata['price']) $mdata['price'] = 500;
            } elseif($offerType == 'prd') {
              $mid = cot_import('prd_id', 'P', 'INT');
              $mitem = $db->query("SELECT * FROM $db_market WHERE item_id=".$mid.' AND item_userid='.$usr['id'].' AND item_state=0 LIMIT 1')->fetch();
              if($mitem['item_id'] > 0) {
                $item_catcostplans = (!empty($mitem['item_catcostplans']) ? json_decode($mitem['item_catcostplans'], 1) : array());
                $mdata = array(
                  'type' => 'offer_prd',
                  'pid' => $mid,
                  'name' => cot_import('prd_name', 'P', 'TXT'),
                  'desc' => cot_import('prd_desc', 'P', 'TXT'),
                  'duration' => 0,
                  'price' => cot_import('prd_price', 'P', 'NUM'),
                  'count' => cot_import('prd_count', 'P', 'INT'),
                  'item_cache' => $mitem,
                  'package_type' => cot_import('prd_package_type', 'P', 'TXT'),
                  'gextras' => cot_import('gextras', 'P', 'ARR'),
                  'gextras_count' => array(),
                  'gextras_custom' => array(),
                  'gextras_selected' => array(), /* для package */
                  'decline' => 0,
                  'orderId' => 0
                );
                if(!$mdata['count']) $mdata['count'] = 1;
                if(empty($mdata['name'])) $mdata['name'] = $mitem['item_title'];
                if(empty($mdata['desc'])) $mdata['desc'] = $mitem['item_text'];

                require_once cot_incfile('catcostplans', 'plug');

                if($item_catcostplans['bundle_type'] == 'package') {
                  $cpdata = cot_get_costplan_bydata($item_catcostplans, $mdata['package_type']);

                  $mdata['gextras_selected'] = $cpdata['bundle'];
                  $mdata['price'] = $cpdata['price'];
                  $mdata['duration'] = $cpdata['days'];
                } else {
                  $mdata['price'] = $mitem['item_cost']*$mdata['count'];
                  $mdata['duration'] = $item_catcostplans['bundles']['category']['time']*$mdata['count'];
                }

                if($item_catcostplans['bundle_type'] == 'single' && count($mdata['gextras']) > 0) {
                  foreach($mdata['gextras'] as $eid) {
                    if(is_array($item_catcostplans['bundles']['custom'][$eid])) {
                      $mdata['gextras_count'][$eid] = cot_import('extra_count'.$eid, 'P', 'INT');
                      if(!$mdata['gextras_count'][$eid]) {
                        $mdata['gextras_count'][$eid] = 0;
                      } else {
                        $mdata['price'] += $costplans_prices[$item_catcostplans['bundles']['custom'][$eid]['price']]*$mdata['gextras_count'][$eid];
                        $mdata['duration'] += $item_catcostplans['bundles']['custom'][$eid]['duration']*$mdata['gextras_count'][$eid];
                      }
                    }
                  }
                }

                $customExtraName = cot_import('customExtraName', 'P', 'ARR');
                $customExtraTime = cot_import('customExtraTime', 'P', 'ARR');
                $customExtraPrice = cot_import('customExtraPrice', 'P', 'ARR');

                foreach($customExtraName as $cid => $cname) {
                  if(!empty($cname)) $mdata['gextras_custom'][] = array(
                    'name' => $cname,
                    'time' => $customExtraTime[$cid],
                    'price' => $costplans_prices[$customExtraPrice[$cid]],
                    'priceId' => $customExtraPrice[$cid],
                  );
                  $mdata['price'] += $costplans_prices[$customExtraPrice[$cid]];
                  $mdata['duration'] += $customExtraTime[$cid];
                }
              }
            }
            $roffer['offer_json'] = $mdata;
            $roffer['offer_json'] = json_encode($roffer['offer_json']);

        		$db->insert($db_projects_offers, $roffer);
        		$offerid = $db->lastInsertId();

            if(!empty($item['user_email'])) {
          		$urlparams = empty($item['item_alias']) ?
          			array('c' => $item['item_cat'], 'id' => $item['item_id']) :
          			array('c' => $item['item_cat'], 'al' => $item['item_alias']);

          		$rsubject = cot_rc($L['project_added_offer_header'], array('prtitle' => $item['item_title']));
          		$rbody = cot_rc($L['project_added_offer_body'], array(
          			'user_name' => $item['user_name'],
          			'offeruser_name' => $usr['profile']['user_name'],
          			'prj_name' => $item['item_title'],
          			'sitename' => $cfg['maintitle'],
          			'link' => COT_ABSOLUTE_URL . cot_url('projects', $urlparams, '', true)
          		));
          		cot_mail($item['user_email'], $rsubject, $rbody);

          		$offerscount = $db->query("SELECT COUNT(*) FROM $db_projects_offers WHERE offer_pid=" . (int)$item['item_id'] . "")->fetchColumn();
          		$db->update($db_projects, array("item_offerscount" => (int)$offerscount), "item_id=" . (int)$item['item_id']);
            }

        		/* === Hook === */
        		foreach (cot_getextplugins('projects.offers.add.done') as $pl)
        		{
        			include $pl;
        		}
        		/* ===== */

            $return['success'] = true;
            $return['redirect'] = cot_url('projects', $urlparams, '', true); //TODO!!!
            $return['error'] = '';
          }
        }
      }
    }
  }
} else {
  $return['error'] = 'Вы не авторизованы';
}

?>
